repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/modules/introspect.py
running_service_owners
def running_service_owners( exclude=('/dev', '/home', '/media', '/proc', '/run', '/sys/', '/tmp', '/var') ): ''' Determine which packages own the currently running services. By default, excludes files whose full path starts with ``/dev``, ``/home``, ``/media``, ``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be overridden by passing in a new list to ``exclude``. CLI Example: salt myminion introspect.running_service_owners ''' error = {} if 'pkg.owner' not in __salt__: error['Unsupported Package Manager'] = ( 'The module for the package manager on this system does not ' 'support looking up which package(s) owns which file(s)' ) if 'file.open_files' not in __salt__: error['Unsupported File Module'] = ( 'The file module on this system does not ' 'support looking up open files on the system' ) if error: return {'Error': error} ret = {} open_files = __salt__['file.open_files']() execs = __salt__['service.execs']() for path in open_files: ignore = False for bad_dir in exclude: if path.startswith(bad_dir): ignore = True if ignore: continue if not os.access(path, os.X_OK): continue for service in execs: if path == execs[service]: pkg = __salt__['pkg.owner'](path) ret[service] = next(six.itervalues(pkg)) return ret
python
def running_service_owners( exclude=('/dev', '/home', '/media', '/proc', '/run', '/sys/', '/tmp', '/var') ): ''' Determine which packages own the currently running services. By default, excludes files whose full path starts with ``/dev``, ``/home``, ``/media``, ``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be overridden by passing in a new list to ``exclude``. CLI Example: salt myminion introspect.running_service_owners ''' error = {} if 'pkg.owner' not in __salt__: error['Unsupported Package Manager'] = ( 'The module for the package manager on this system does not ' 'support looking up which package(s) owns which file(s)' ) if 'file.open_files' not in __salt__: error['Unsupported File Module'] = ( 'The file module on this system does not ' 'support looking up open files on the system' ) if error: return {'Error': error} ret = {} open_files = __salt__['file.open_files']() execs = __salt__['service.execs']() for path in open_files: ignore = False for bad_dir in exclude: if path.startswith(bad_dir): ignore = True if ignore: continue if not os.access(path, os.X_OK): continue for service in execs: if path == execs[service]: pkg = __salt__['pkg.owner'](path) ret[service] = next(six.itervalues(pkg)) return ret
[ "def", "running_service_owners", "(", "exclude", "=", "(", "'/dev'", ",", "'/home'", ",", "'/media'", ",", "'/proc'", ",", "'/run'", ",", "'/sys/'", ",", "'/tmp'", ",", "'/var'", ")", ")", ":", "error", "=", "{", "}", "if", "'pkg.owner'", "not", "in", ...
Determine which packages own the currently running services. By default, excludes files whose full path starts with ``/dev``, ``/home``, ``/media``, ``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be overridden by passing in a new list to ``exclude``. CLI Example: salt myminion introspect.running_service_owners
[ "Determine", "which", "packages", "own", "the", "currently", "running", "services", ".", "By", "default", "excludes", "files", "whose", "full", "path", "starts", "with", "/", "dev", "/", "home", "/", "media", "/", "proc", "/", "run", "/", "sys", "/", "tm...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/introspect.py#L15-L66
train
saltstack/salt
salt/modules/introspect.py
enabled_service_owners
def enabled_service_owners(): ''' Return which packages own each of the services that are currently enabled. CLI Example: salt myminion introspect.enabled_service_owners ''' error = {} if 'pkg.owner' not in __salt__: error['Unsupported Package Manager'] = ( 'The module for the package manager on this system does not ' 'support looking up which package(s) owns which file(s)' ) if 'service.show' not in __salt__: error['Unsupported Service Manager'] = ( 'The module for the service manager on this system does not ' 'support showing descriptive service data' ) if error: return {'Error': error} ret = {} services = __salt__['service.get_enabled']() for service in services: data = __salt__['service.show'](service) if 'ExecStart' not in data: continue start_cmd = data['ExecStart']['path'] pkg = __salt__['pkg.owner'](start_cmd) ret[service] = next(six.itervalues(pkg)) return ret
python
def enabled_service_owners(): ''' Return which packages own each of the services that are currently enabled. CLI Example: salt myminion introspect.enabled_service_owners ''' error = {} if 'pkg.owner' not in __salt__: error['Unsupported Package Manager'] = ( 'The module for the package manager on this system does not ' 'support looking up which package(s) owns which file(s)' ) if 'service.show' not in __salt__: error['Unsupported Service Manager'] = ( 'The module for the service manager on this system does not ' 'support showing descriptive service data' ) if error: return {'Error': error} ret = {} services = __salt__['service.get_enabled']() for service in services: data = __salt__['service.show'](service) if 'ExecStart' not in data: continue start_cmd = data['ExecStart']['path'] pkg = __salt__['pkg.owner'](start_cmd) ret[service] = next(six.itervalues(pkg)) return ret
[ "def", "enabled_service_owners", "(", ")", ":", "error", "=", "{", "}", "if", "'pkg.owner'", "not", "in", "__salt__", ":", "error", "[", "'Unsupported Package Manager'", "]", "=", "(", "'The module for the package manager on this system does not '", "'support looking up w...
Return which packages own each of the services that are currently enabled. CLI Example: salt myminion introspect.enabled_service_owners
[ "Return", "which", "packages", "own", "each", "of", "the", "services", "that", "are", "currently", "enabled", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/introspect.py#L69-L104
train
saltstack/salt
salt/modules/introspect.py
service_highstate
def service_highstate(requires=True): ''' Return running and enabled services in a highstate structure. By default also returns package dependencies for those services, which means that package definitions must be created outside this function. To drop the package dependencies, set ``requires`` to False. CLI Example: salt myminion introspect.service_highstate salt myminion introspect.service_highstate requires=False ''' ret = {} running = running_service_owners() for service in running: ret[service] = {'service': ['running']} if requires: ret[service]['service'].append( {'require': {'pkg': running[service]}} ) enabled = enabled_service_owners() for service in enabled: if service in ret: ret[service]['service'].append({'enabled': True}) else: ret[service] = {'service': [{'enabled': True}]} if requires: exists = False for item in ret[service]['service']: if isinstance(item, dict) and next(six.iterkeys(item)) == 'require': exists = True if not exists: ret[service]['service'].append( {'require': {'pkg': enabled[service]}} ) return ret
python
def service_highstate(requires=True): ''' Return running and enabled services in a highstate structure. By default also returns package dependencies for those services, which means that package definitions must be created outside this function. To drop the package dependencies, set ``requires`` to False. CLI Example: salt myminion introspect.service_highstate salt myminion introspect.service_highstate requires=False ''' ret = {} running = running_service_owners() for service in running: ret[service] = {'service': ['running']} if requires: ret[service]['service'].append( {'require': {'pkg': running[service]}} ) enabled = enabled_service_owners() for service in enabled: if service in ret: ret[service]['service'].append({'enabled': True}) else: ret[service] = {'service': [{'enabled': True}]} if requires: exists = False for item in ret[service]['service']: if isinstance(item, dict) and next(six.iterkeys(item)) == 'require': exists = True if not exists: ret[service]['service'].append( {'require': {'pkg': enabled[service]}} ) return ret
[ "def", "service_highstate", "(", "requires", "=", "True", ")", ":", "ret", "=", "{", "}", "running", "=", "running_service_owners", "(", ")", "for", "service", "in", "running", ":", "ret", "[", "service", "]", "=", "{", "'service'", ":", "[", "'running'"...
Return running and enabled services in a highstate structure. By default also returns package dependencies for those services, which means that package definitions must be created outside this function. To drop the package dependencies, set ``requires`` to False. CLI Example: salt myminion introspect.service_highstate salt myminion introspect.service_highstate requires=False
[ "Return", "running", "and", "enabled", "services", "in", "a", "highstate", "structure", ".", "By", "default", "also", "returns", "package", "dependencies", "for", "those", "services", "which", "means", "that", "package", "definitions", "must", "be", "created", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/introspect.py#L107-L146
train
saltstack/salt
salt/roster/clustershell.py
targets
def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets ''' ret = {} ports = __opts__['ssh_scan_ports'] if not isinstance(ports, list): # Comma-separate list of integers ports = list(map(int, six.text_type(ports).split(','))) hosts = list(NodeSet(tgt)) host_addrs = dict([(h, socket.gethostbyname(h)) for h in hosts]) for host, addr in host_addrs.items(): addr = six.text_type(addr) ret[host] = copy.deepcopy(__opts__.get('roster_defaults', {})) for port in ports: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(float(__opts__['ssh_scan_timeout'])) sock.connect((addr, port)) sock.shutdown(socket.SHUT_RDWR) sock.close() ret[host].update({'host': addr, 'port': port}) except socket.error: pass return ret
python
def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets ''' ret = {} ports = __opts__['ssh_scan_ports'] if not isinstance(ports, list): # Comma-separate list of integers ports = list(map(int, six.text_type(ports).split(','))) hosts = list(NodeSet(tgt)) host_addrs = dict([(h, socket.gethostbyname(h)) for h in hosts]) for host, addr in host_addrs.items(): addr = six.text_type(addr) ret[host] = copy.deepcopy(__opts__.get('roster_defaults', {})) for port in ports: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(float(__opts__['ssh_scan_timeout'])) sock.connect((addr, port)) sock.shutdown(socket.SHUT_RDWR) sock.close() ret[host].update({'host': addr, 'port': port}) except socket.error: pass return ret
[ "def", "targets", "(", "tgt", ",", "tgt_type", "=", "'glob'", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "ports", "=", "__opts__", "[", "'ssh_scan_ports'", "]", "if", "not", "isinstance", "(", "ports", ",", "list", ")", ":", "# Comma-se...
Return the targets
[ "Return", "the", "targets" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/clustershell.py#L33-L59
train
saltstack/salt
salt/config/__init__.py
_gather_buffer_space
def _gather_buffer_space(): ''' Gather some system data and then calculate buffer space. Result is in bytes. ''' if HAS_PSUTIL and psutil.version_info >= (0, 6, 0): # Oh good, we have psutil. This will be quick. total_mem = psutil.virtual_memory().total else: # Avoid loading core grains unless absolutely required import platform import salt.grains.core # We need to load up ``mem_total`` grain. Let's mimic required OS data. os_data = {'kernel': platform.system()} grains = salt.grains.core._memdata(os_data) total_mem = grains['mem_total'] * 1024 * 1024 # Return the higher number between 5% of the system memory and 10MiB return max([total_mem * 0.05, 10 << 20])
python
def _gather_buffer_space(): ''' Gather some system data and then calculate buffer space. Result is in bytes. ''' if HAS_PSUTIL and psutil.version_info >= (0, 6, 0): # Oh good, we have psutil. This will be quick. total_mem = psutil.virtual_memory().total else: # Avoid loading core grains unless absolutely required import platform import salt.grains.core # We need to load up ``mem_total`` grain. Let's mimic required OS data. os_data = {'kernel': platform.system()} grains = salt.grains.core._memdata(os_data) total_mem = grains['mem_total'] * 1024 * 1024 # Return the higher number between 5% of the system memory and 10MiB return max([total_mem * 0.05, 10 << 20])
[ "def", "_gather_buffer_space", "(", ")", ":", "if", "HAS_PSUTIL", "and", "psutil", ".", "version_info", ">=", "(", "0", ",", "6", ",", "0", ")", ":", "# Oh good, we have psutil. This will be quick.", "total_mem", "=", "psutil", ".", "virtual_memory", "(", ")", ...
Gather some system data and then calculate buffer space. Result is in bytes.
[ "Gather", "some", "system", "data", "and", "then", "calculate", "buffer", "space", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L76-L95
train
saltstack/salt
salt/config/__init__.py
_normalize_roots
def _normalize_roots(file_roots): ''' Normalize file or pillar roots. ''' for saltenv, dirs in six.iteritems(file_roots): normalized_saltenv = six.text_type(saltenv) if normalized_saltenv != saltenv: file_roots[normalized_saltenv] = file_roots.pop(saltenv) if not isinstance(dirs, (list, tuple)): file_roots[normalized_saltenv] = [] file_roots[normalized_saltenv] = \ _expand_glob_path(file_roots[normalized_saltenv]) return file_roots
python
def _normalize_roots(file_roots): ''' Normalize file or pillar roots. ''' for saltenv, dirs in six.iteritems(file_roots): normalized_saltenv = six.text_type(saltenv) if normalized_saltenv != saltenv: file_roots[normalized_saltenv] = file_roots.pop(saltenv) if not isinstance(dirs, (list, tuple)): file_roots[normalized_saltenv] = [] file_roots[normalized_saltenv] = \ _expand_glob_path(file_roots[normalized_saltenv]) return file_roots
[ "def", "_normalize_roots", "(", "file_roots", ")", ":", "for", "saltenv", ",", "dirs", "in", "six", ".", "iteritems", "(", "file_roots", ")", ":", "normalized_saltenv", "=", "six", ".", "text_type", "(", "saltenv", ")", "if", "normalized_saltenv", "!=", "sal...
Normalize file or pillar roots.
[ "Normalize", "file", "or", "pillar", "roots", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L1956-L1968
train
saltstack/salt
salt/config/__init__.py
_validate_pillar_roots
def _validate_pillar_roots(pillar_roots): ''' If the pillar_roots option has a key that is None then we will error out, just replace it with an empty list ''' if not isinstance(pillar_roots, dict): log.warning('The pillar_roots parameter is not properly formatted,' ' using defaults') return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])} return _normalize_roots(pillar_roots)
python
def _validate_pillar_roots(pillar_roots): ''' If the pillar_roots option has a key that is None then we will error out, just replace it with an empty list ''' if not isinstance(pillar_roots, dict): log.warning('The pillar_roots parameter is not properly formatted,' ' using defaults') return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])} return _normalize_roots(pillar_roots)
[ "def", "_validate_pillar_roots", "(", "pillar_roots", ")", ":", "if", "not", "isinstance", "(", "pillar_roots", ",", "dict", ")", ":", "log", ".", "warning", "(", "'The pillar_roots parameter is not properly formatted,'", "' using defaults'", ")", "return", "{", "'bas...
If the pillar_roots option has a key that is None then we will error out, just replace it with an empty list
[ "If", "the", "pillar_roots", "option", "has", "a", "key", "that", "is", "None", "then", "we", "will", "error", "out", "just", "replace", "it", "with", "an", "empty", "list" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L1971-L1980
train
saltstack/salt
salt/config/__init__.py
_validate_file_roots
def _validate_file_roots(file_roots): ''' If the file_roots option has a key that is None then we will error out, just replace it with an empty list ''' if not isinstance(file_roots, dict): log.warning('The file_roots parameter is not properly formatted,' ' using defaults') return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])} return _normalize_roots(file_roots)
python
def _validate_file_roots(file_roots): ''' If the file_roots option has a key that is None then we will error out, just replace it with an empty list ''' if not isinstance(file_roots, dict): log.warning('The file_roots parameter is not properly formatted,' ' using defaults') return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])} return _normalize_roots(file_roots)
[ "def", "_validate_file_roots", "(", "file_roots", ")", ":", "if", "not", "isinstance", "(", "file_roots", ",", "dict", ")", ":", "log", ".", "warning", "(", "'The file_roots parameter is not properly formatted,'", "' using defaults'", ")", "return", "{", "'base'", "...
If the file_roots option has a key that is None then we will error out, just replace it with an empty list
[ "If", "the", "file_roots", "option", "has", "a", "key", "that", "is", "None", "then", "we", "will", "error", "out", "just", "replace", "it", "with", "an", "empty", "list" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L1983-L1992
train
saltstack/salt
salt/config/__init__.py
_expand_glob_path
def _expand_glob_path(file_roots): ''' Applies shell globbing to a set of directories and returns the expanded paths ''' unglobbed_path = [] for path in file_roots: try: if glob.has_magic(path): unglobbed_path.extend(glob.glob(path)) else: unglobbed_path.append(path) except Exception: unglobbed_path.append(path) return unglobbed_path
python
def _expand_glob_path(file_roots): ''' Applies shell globbing to a set of directories and returns the expanded paths ''' unglobbed_path = [] for path in file_roots: try: if glob.has_magic(path): unglobbed_path.extend(glob.glob(path)) else: unglobbed_path.append(path) except Exception: unglobbed_path.append(path) return unglobbed_path
[ "def", "_expand_glob_path", "(", "file_roots", ")", ":", "unglobbed_path", "=", "[", "]", "for", "path", "in", "file_roots", ":", "try", ":", "if", "glob", ".", "has_magic", "(", "path", ")", ":", "unglobbed_path", ".", "extend", "(", "glob", ".", "glob"...
Applies shell globbing to a set of directories and returns the expanded paths
[ "Applies", "shell", "globbing", "to", "a", "set", "of", "directories", "and", "returns", "the", "expanded", "paths" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L1995-L2009
train
saltstack/salt
salt/config/__init__.py
_validate_opts
def _validate_opts(opts): ''' Check that all of the types of values passed into the config are of the right types ''' def format_multi_opt(valid_type): try: num_types = len(valid_type) except TypeError: # Bare type name won't have a length, return the name of the type # passed. return valid_type.__name__ else: def get_types(types, type_tuple): for item in type_tuple: if isinstance(item, tuple): get_types(types, item) else: try: types.append(item.__name__) except AttributeError: log.warning( 'Unable to interpret type %s while validating ' 'configuration', item ) types = [] get_types(types, valid_type) ret = ', '.join(types[:-1]) ret += ' or ' + types[-1] return ret errors = [] err = ( 'Config option \'{0}\' with value {1} has an invalid type of {2}, a ' '{3} is required for this option' ) for key, val in six.iteritems(opts): if key in VALID_OPTS: if val is None: if VALID_OPTS[key] is None: continue else: try: if None in VALID_OPTS[key]: continue except TypeError: # VALID_OPTS[key] is not iterable and not None pass if isinstance(val, VALID_OPTS[key]): continue # We don't know what data type sdb will return at run-time so we # simply cannot check it for correctness here at start-time. if isinstance(val, six.string_types) and val.startswith('sdb://'): continue if hasattr(VALID_OPTS[key], '__call__'): try: VALID_OPTS[key](val) if isinstance(val, (list, dict)): # We'll only get here if VALID_OPTS[key] is str or # bool, and the passed value is a list/dict. Attempting # to run int() or float() on a list/dict will raise an # exception, but running str() or bool() on it will # pass despite not being the correct type. errors.append( err.format( key, val, type(val).__name__, VALID_OPTS[key].__name__ ) ) except (TypeError, ValueError): errors.append( err.format(key, val, type(val).__name__, VALID_OPTS[key].__name__) ) continue errors.append( err.format(key, val, type(val).__name__, format_multi_opt(VALID_OPTS[key])) ) # Convert list to comma-delimited string for 'return' config option if isinstance(opts.get('return'), list): opts['return'] = ','.join(opts['return']) for error in errors: log.warning(error) if errors: return False return True
python
def _validate_opts(opts): ''' Check that all of the types of values passed into the config are of the right types ''' def format_multi_opt(valid_type): try: num_types = len(valid_type) except TypeError: # Bare type name won't have a length, return the name of the type # passed. return valid_type.__name__ else: def get_types(types, type_tuple): for item in type_tuple: if isinstance(item, tuple): get_types(types, item) else: try: types.append(item.__name__) except AttributeError: log.warning( 'Unable to interpret type %s while validating ' 'configuration', item ) types = [] get_types(types, valid_type) ret = ', '.join(types[:-1]) ret += ' or ' + types[-1] return ret errors = [] err = ( 'Config option \'{0}\' with value {1} has an invalid type of {2}, a ' '{3} is required for this option' ) for key, val in six.iteritems(opts): if key in VALID_OPTS: if val is None: if VALID_OPTS[key] is None: continue else: try: if None in VALID_OPTS[key]: continue except TypeError: # VALID_OPTS[key] is not iterable and not None pass if isinstance(val, VALID_OPTS[key]): continue # We don't know what data type sdb will return at run-time so we # simply cannot check it for correctness here at start-time. if isinstance(val, six.string_types) and val.startswith('sdb://'): continue if hasattr(VALID_OPTS[key], '__call__'): try: VALID_OPTS[key](val) if isinstance(val, (list, dict)): # We'll only get here if VALID_OPTS[key] is str or # bool, and the passed value is a list/dict. Attempting # to run int() or float() on a list/dict will raise an # exception, but running str() or bool() on it will # pass despite not being the correct type. errors.append( err.format( key, val, type(val).__name__, VALID_OPTS[key].__name__ ) ) except (TypeError, ValueError): errors.append( err.format(key, val, type(val).__name__, VALID_OPTS[key].__name__) ) continue errors.append( err.format(key, val, type(val).__name__, format_multi_opt(VALID_OPTS[key])) ) # Convert list to comma-delimited string for 'return' config option if isinstance(opts.get('return'), list): opts['return'] = ','.join(opts['return']) for error in errors: log.warning(error) if errors: return False return True
[ "def", "_validate_opts", "(", "opts", ")", ":", "def", "format_multi_opt", "(", "valid_type", ")", ":", "try", ":", "num_types", "=", "len", "(", "valid_type", ")", "except", "TypeError", ":", "# Bare type name won't have a length, return the name of the type", "# pas...
Check that all of the types of values passed into the config are of the right types
[ "Check", "that", "all", "of", "the", "types", "of", "values", "passed", "into", "the", "config", "are", "of", "the", "right", "types" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2012-L2112
train
saltstack/salt
salt/config/__init__.py
_validate_ssh_minion_opts
def _validate_ssh_minion_opts(opts): ''' Ensure we're not using any invalid ssh_minion_opts. We want to make sure that the ssh_minion_opts does not override any pillar or fileserver options inherited from the master config. To add other items, modify the if statement in the for loop below. ''' ssh_minion_opts = opts.get('ssh_minion_opts', {}) if not isinstance(ssh_minion_opts, dict): log.error('Invalidly-formatted ssh_minion_opts') opts.pop('ssh_minion_opts') for opt_name in list(ssh_minion_opts): if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \ or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \ or opt_name in ('fileserver_backend',): log.warning( '\'%s\' is not a valid ssh_minion_opts parameter, ignoring', opt_name ) ssh_minion_opts.pop(opt_name)
python
def _validate_ssh_minion_opts(opts): ''' Ensure we're not using any invalid ssh_minion_opts. We want to make sure that the ssh_minion_opts does not override any pillar or fileserver options inherited from the master config. To add other items, modify the if statement in the for loop below. ''' ssh_minion_opts = opts.get('ssh_minion_opts', {}) if not isinstance(ssh_minion_opts, dict): log.error('Invalidly-formatted ssh_minion_opts') opts.pop('ssh_minion_opts') for opt_name in list(ssh_minion_opts): if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \ or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \ or opt_name in ('fileserver_backend',): log.warning( '\'%s\' is not a valid ssh_minion_opts parameter, ignoring', opt_name ) ssh_minion_opts.pop(opt_name)
[ "def", "_validate_ssh_minion_opts", "(", "opts", ")", ":", "ssh_minion_opts", "=", "opts", ".", "get", "(", "'ssh_minion_opts'", ",", "{", "}", ")", "if", "not", "isinstance", "(", "ssh_minion_opts", ",", "dict", ")", ":", "log", ".", "error", "(", "'Inval...
Ensure we're not using any invalid ssh_minion_opts. We want to make sure that the ssh_minion_opts does not override any pillar or fileserver options inherited from the master config. To add other items, modify the if statement in the for loop below.
[ "Ensure", "we", "re", "not", "using", "any", "invalid", "ssh_minion_opts", ".", "We", "want", "to", "make", "sure", "that", "the", "ssh_minion_opts", "does", "not", "override", "any", "pillar", "or", "fileserver", "options", "inherited", "from", "the", "master...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2115-L2135
train
saltstack/salt
salt/config/__init__.py
_append_domain
def _append_domain(opts): ''' Append a domain to the existing id if it doesn't already exist ''' # Domain already exists if opts['id'].endswith(opts['append_domain']): return opts['id'] # Trailing dot should mean an FQDN that is terminated, leave it alone. if opts['id'].endswith('.'): return opts['id'] return '{0[id]}.{0[append_domain]}'.format(opts)
python
def _append_domain(opts): ''' Append a domain to the existing id if it doesn't already exist ''' # Domain already exists if opts['id'].endswith(opts['append_domain']): return opts['id'] # Trailing dot should mean an FQDN that is terminated, leave it alone. if opts['id'].endswith('.'): return opts['id'] return '{0[id]}.{0[append_domain]}'.format(opts)
[ "def", "_append_domain", "(", "opts", ")", ":", "# Domain already exists", "if", "opts", "[", "'id'", "]", ".", "endswith", "(", "opts", "[", "'append_domain'", "]", ")", ":", "return", "opts", "[", "'id'", "]", "# Trailing dot should mean an FQDN that is terminat...
Append a domain to the existing id if it doesn't already exist
[ "Append", "a", "domain", "to", "the", "existing", "id", "if", "it", "doesn", "t", "already", "exist" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2138-L2148
train
saltstack/salt
salt/config/__init__.py
_read_conf_file
def _read_conf_file(path): ''' Read in a config file from a given path and process it into a dictionary ''' log.debug('Reading configuration from %s', path) with salt.utils.files.fopen(path, 'r') as conf_file: try: conf_opts = salt.utils.yaml.safe_load(conf_file) or {} except salt.utils.yaml.YAMLError as err: message = 'Error parsing configuration file: {0} - {1}'.format(path, err) log.error(message) raise salt.exceptions.SaltConfigurationError(message) # only interpret documents as a valid conf, not things like strings, # which might have been caused by invalid yaml syntax if not isinstance(conf_opts, dict): message = 'Error parsing configuration file: {0} - conf ' \ 'should be a document, not {1}.'.format(path, type(conf_opts)) log.error(message) raise salt.exceptions.SaltConfigurationError(message) # allow using numeric ids: convert int to string if 'id' in conf_opts: if not isinstance(conf_opts['id'], six.string_types): conf_opts['id'] = six.text_type(conf_opts['id']) else: conf_opts['id'] = salt.utils.data.decode(conf_opts['id']) return conf_opts
python
def _read_conf_file(path): ''' Read in a config file from a given path and process it into a dictionary ''' log.debug('Reading configuration from %s', path) with salt.utils.files.fopen(path, 'r') as conf_file: try: conf_opts = salt.utils.yaml.safe_load(conf_file) or {} except salt.utils.yaml.YAMLError as err: message = 'Error parsing configuration file: {0} - {1}'.format(path, err) log.error(message) raise salt.exceptions.SaltConfigurationError(message) # only interpret documents as a valid conf, not things like strings, # which might have been caused by invalid yaml syntax if not isinstance(conf_opts, dict): message = 'Error parsing configuration file: {0} - conf ' \ 'should be a document, not {1}.'.format(path, type(conf_opts)) log.error(message) raise salt.exceptions.SaltConfigurationError(message) # allow using numeric ids: convert int to string if 'id' in conf_opts: if not isinstance(conf_opts['id'], six.string_types): conf_opts['id'] = six.text_type(conf_opts['id']) else: conf_opts['id'] = salt.utils.data.decode(conf_opts['id']) return conf_opts
[ "def", "_read_conf_file", "(", "path", ")", ":", "log", ".", "debug", "(", "'Reading configuration from %s'", ",", "path", ")", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'r'", ")", "as", "conf_file", ":", "try", ":", ...
Read in a config file from a given path and process it into a dictionary
[ "Read", "in", "a", "config", "file", "from", "a", "given", "path", "and", "process", "it", "into", "a", "dictionary" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2151-L2178
train
saltstack/salt
salt/config/__init__.py
_absolute_path
def _absolute_path(path, relative_to=None): ''' Return an absolute path. In case ``relative_to`` is passed and ``path`` is not an absolute path, we try to prepend ``relative_to`` to ``path``and if that path exists, return that one ''' if path and os.path.isabs(path): return path if path and relative_to is not None: _abspath = os.path.join(relative_to, path) if os.path.isfile(_abspath): log.debug( 'Relative path \'%s\' converted to existing absolute path ' '\'%s\'', path, _abspath ) return _abspath return path
python
def _absolute_path(path, relative_to=None): ''' Return an absolute path. In case ``relative_to`` is passed and ``path`` is not an absolute path, we try to prepend ``relative_to`` to ``path``and if that path exists, return that one ''' if path and os.path.isabs(path): return path if path and relative_to is not None: _abspath = os.path.join(relative_to, path) if os.path.isfile(_abspath): log.debug( 'Relative path \'%s\' converted to existing absolute path ' '\'%s\'', path, _abspath ) return _abspath return path
[ "def", "_absolute_path", "(", "path", ",", "relative_to", "=", "None", ")", ":", "if", "path", "and", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "if", "path", "and", "relative_to", "is", "not", "None", ":", "_abspath", ...
Return an absolute path. In case ``relative_to`` is passed and ``path`` is not an absolute path, we try to prepend ``relative_to`` to ``path``and if that path exists, return that one
[ "Return", "an", "absolute", "path", ".", "In", "case", "relative_to", "is", "passed", "and", "path", "is", "not", "an", "absolute", "path", "we", "try", "to", "prepend", "relative_to", "to", "path", "and", "if", "that", "path", "exists", "return", "that", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2181-L2198
train
saltstack/salt
salt/config/__init__.py
load_config
def load_config(path, env_var, default_path=None, exit_on_config_errors=True): ''' Returns configuration dict from parsing either the file described by ``path`` or the environment variable described by ``env_var`` as YAML. ''' if path is None: # When the passed path is None, we just want the configuration # defaults, not actually loading the whole configuration. return {} if default_path is None: # This is most likely not being used from salt, i.e., could be salt-cloud # or salt-api which have not yet migrated to the new default_path # argument. Let's issue a warning message that the environ vars won't # work. import inspect previous_frame = inspect.getframeinfo(inspect.currentframe().f_back) log.warning( "The function '%s()' defined in '%s' is not yet using the " "new 'default_path' argument to `salt.config.load_config()`. " "As such, the '%s' environment variable will be ignored", previous_frame.function, previous_frame.filename, env_var ) # In this case, maintain old behavior default_path = DEFAULT_MASTER_OPTS['conf_file'] # Default to the environment variable path, if it exists env_path = os.environ.get(env_var, path) if not env_path or not os.path.isfile(env_path): env_path = path # If non-default path from `-c`, use that over the env variable if path != default_path: env_path = path path = env_path # If the configuration file is missing, attempt to copy the template, # after removing the first header line. if not os.path.isfile(path): template = '{0}.template'.format(path) if os.path.isfile(template): log.debug('Writing %s based on %s', path, template) with salt.utils.files.fopen(path, 'w') as out: with salt.utils.files.fopen(template, 'r') as ifile: ifile.readline() # skip first line out.write(ifile.read()) opts = {} if salt.utils.validate.path.is_readable(path): try: opts = _read_conf_file(path) opts['conf_file'] = path except salt.exceptions.SaltConfigurationError as error: log.error(error) if exit_on_config_errors: sys.exit(salt.defaults.exitcodes.EX_GENERIC) else: log.debug('Missing configuration file: %s', path) return opts
python
def load_config(path, env_var, default_path=None, exit_on_config_errors=True): ''' Returns configuration dict from parsing either the file described by ``path`` or the environment variable described by ``env_var`` as YAML. ''' if path is None: # When the passed path is None, we just want the configuration # defaults, not actually loading the whole configuration. return {} if default_path is None: # This is most likely not being used from salt, i.e., could be salt-cloud # or salt-api which have not yet migrated to the new default_path # argument. Let's issue a warning message that the environ vars won't # work. import inspect previous_frame = inspect.getframeinfo(inspect.currentframe().f_back) log.warning( "The function '%s()' defined in '%s' is not yet using the " "new 'default_path' argument to `salt.config.load_config()`. " "As such, the '%s' environment variable will be ignored", previous_frame.function, previous_frame.filename, env_var ) # In this case, maintain old behavior default_path = DEFAULT_MASTER_OPTS['conf_file'] # Default to the environment variable path, if it exists env_path = os.environ.get(env_var, path) if not env_path or not os.path.isfile(env_path): env_path = path # If non-default path from `-c`, use that over the env variable if path != default_path: env_path = path path = env_path # If the configuration file is missing, attempt to copy the template, # after removing the first header line. if not os.path.isfile(path): template = '{0}.template'.format(path) if os.path.isfile(template): log.debug('Writing %s based on %s', path, template) with salt.utils.files.fopen(path, 'w') as out: with salt.utils.files.fopen(template, 'r') as ifile: ifile.readline() # skip first line out.write(ifile.read()) opts = {} if salt.utils.validate.path.is_readable(path): try: opts = _read_conf_file(path) opts['conf_file'] = path except salt.exceptions.SaltConfigurationError as error: log.error(error) if exit_on_config_errors: sys.exit(salt.defaults.exitcodes.EX_GENERIC) else: log.debug('Missing configuration file: %s', path) return opts
[ "def", "load_config", "(", "path", ",", "env_var", ",", "default_path", "=", "None", ",", "exit_on_config_errors", "=", "True", ")", ":", "if", "path", "is", "None", ":", "# When the passed path is None, we just want the configuration", "# defaults, not actually loading t...
Returns configuration dict from parsing either the file described by ``path`` or the environment variable described by ``env_var`` as YAML.
[ "Returns", "configuration", "dict", "from", "parsing", "either", "the", "file", "described", "by", "path", "or", "the", "environment", "variable", "described", "by", "env_var", "as", "YAML", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2201-L2261
train
saltstack/salt
salt/config/__init__.py
include_config
def include_config(include, orig_path, verbose, exit_on_config_errors=False): ''' Parses extra configuration file(s) specified in an include list in the main config file. ''' # Protect against empty option if not include: return {} if orig_path is None: # When the passed path is None, we just want the configuration # defaults, not actually loading the whole configuration. return {} if isinstance(include, six.string_types): include = [include] configuration = {} for path in include: # Allow for includes like ~/foo path = os.path.expanduser(path) if not os.path.isabs(path): path = os.path.join(os.path.dirname(orig_path), path) # Catch situation where user typos path in configuration; also warns # for empty include directory (which might be by design) glob_matches = glob.glob(path) if not glob_matches: if verbose: log.warning( 'Warning parsing configuration file: "include" path/glob ' "'%s' matches no files", path ) for fn_ in sorted(glob_matches): log.debug('Including configuration from \'%s\'', fn_) try: opts = _read_conf_file(fn_) except salt.exceptions.SaltConfigurationError as error: log.error(error) if exit_on_config_errors: sys.exit(salt.defaults.exitcodes.EX_GENERIC) else: # Initialize default config if we wish to skip config errors opts = {} schedule = opts.get('schedule', {}) if schedule and 'schedule' in configuration: configuration['schedule'].update(schedule) include = opts.get('include', []) if include: opts.update(include_config(include, fn_, verbose)) salt.utils.dictupdate.update(configuration, opts, True, True) return configuration
python
def include_config(include, orig_path, verbose, exit_on_config_errors=False): ''' Parses extra configuration file(s) specified in an include list in the main config file. ''' # Protect against empty option if not include: return {} if orig_path is None: # When the passed path is None, we just want the configuration # defaults, not actually loading the whole configuration. return {} if isinstance(include, six.string_types): include = [include] configuration = {} for path in include: # Allow for includes like ~/foo path = os.path.expanduser(path) if not os.path.isabs(path): path = os.path.join(os.path.dirname(orig_path), path) # Catch situation where user typos path in configuration; also warns # for empty include directory (which might be by design) glob_matches = glob.glob(path) if not glob_matches: if verbose: log.warning( 'Warning parsing configuration file: "include" path/glob ' "'%s' matches no files", path ) for fn_ in sorted(glob_matches): log.debug('Including configuration from \'%s\'', fn_) try: opts = _read_conf_file(fn_) except salt.exceptions.SaltConfigurationError as error: log.error(error) if exit_on_config_errors: sys.exit(salt.defaults.exitcodes.EX_GENERIC) else: # Initialize default config if we wish to skip config errors opts = {} schedule = opts.get('schedule', {}) if schedule and 'schedule' in configuration: configuration['schedule'].update(schedule) include = opts.get('include', []) if include: opts.update(include_config(include, fn_, verbose)) salt.utils.dictupdate.update(configuration, opts, True, True) return configuration
[ "def", "include_config", "(", "include", ",", "orig_path", ",", "verbose", ",", "exit_on_config_errors", "=", "False", ")", ":", "# Protect against empty option", "if", "not", "include", ":", "return", "{", "}", "if", "orig_path", "is", "None", ":", "# When the ...
Parses extra configuration file(s) specified in an include list in the main config file.
[ "Parses", "extra", "configuration", "file", "(", "s", ")", "specified", "in", "an", "include", "list", "in", "the", "main", "config", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2264-L2318
train
saltstack/salt
salt/config/__init__.py
prepend_root_dir
def prepend_root_dir(opts, path_options): ''' Prepends the options that represent filesystem paths with value of the 'root_dir' option. ''' root_dir = os.path.abspath(opts['root_dir']) def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep) for path_option in path_options: if path_option in opts: path = opts[path_option] tmp_path_def_root_dir = None tmp_path_root_dir = None # When running testsuite, salt.syspaths.ROOT_DIR is often empty if path == def_root_dir or path.startswith(def_root_dir + os.sep): # Remove the default root dir prefix tmp_path_def_root_dir = path[len(def_root_dir):] if root_dir and (path == root_dir or path.startswith(root_dir + os.sep)): # Remove the root dir prefix tmp_path_root_dir = path[len(root_dir):] if tmp_path_def_root_dir and not tmp_path_root_dir: # Just the default root dir matched path = tmp_path_def_root_dir elif tmp_path_root_dir and not tmp_path_def_root_dir: # Just the root dir matched path = tmp_path_root_dir elif tmp_path_def_root_dir and tmp_path_root_dir: # In this case both the default root dir and the override root # dir matched; this means that either # def_root_dir is a substring of root_dir or vice versa # We must choose the most specific path if def_root_dir in root_dir: path = tmp_path_root_dir else: path = tmp_path_def_root_dir elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]: # In windows, os.path.isabs resolves '/' to 'C:\\' or whatever # the root drive is. This elif prevents the next from being # hit, so that the root_dir is prefixed in cases where the # drive is not prefixed on a config option pass elif os.path.isabs(path): # Absolute path (not default or overridden root_dir) # No prepending required continue # Prepending the root dir opts[path_option] = salt.utils.path.join(root_dir, path)
python
def prepend_root_dir(opts, path_options): ''' Prepends the options that represent filesystem paths with value of the 'root_dir' option. ''' root_dir = os.path.abspath(opts['root_dir']) def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep) for path_option in path_options: if path_option in opts: path = opts[path_option] tmp_path_def_root_dir = None tmp_path_root_dir = None # When running testsuite, salt.syspaths.ROOT_DIR is often empty if path == def_root_dir or path.startswith(def_root_dir + os.sep): # Remove the default root dir prefix tmp_path_def_root_dir = path[len(def_root_dir):] if root_dir and (path == root_dir or path.startswith(root_dir + os.sep)): # Remove the root dir prefix tmp_path_root_dir = path[len(root_dir):] if tmp_path_def_root_dir and not tmp_path_root_dir: # Just the default root dir matched path = tmp_path_def_root_dir elif tmp_path_root_dir and not tmp_path_def_root_dir: # Just the root dir matched path = tmp_path_root_dir elif tmp_path_def_root_dir and tmp_path_root_dir: # In this case both the default root dir and the override root # dir matched; this means that either # def_root_dir is a substring of root_dir or vice versa # We must choose the most specific path if def_root_dir in root_dir: path = tmp_path_root_dir else: path = tmp_path_def_root_dir elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]: # In windows, os.path.isabs resolves '/' to 'C:\\' or whatever # the root drive is. This elif prevents the next from being # hit, so that the root_dir is prefixed in cases where the # drive is not prefixed on a config option pass elif os.path.isabs(path): # Absolute path (not default or overridden root_dir) # No prepending required continue # Prepending the root dir opts[path_option] = salt.utils.path.join(root_dir, path)
[ "def", "prepend_root_dir", "(", "opts", ",", "path_options", ")", ":", "root_dir", "=", "os", ".", "path", ".", "abspath", "(", "opts", "[", "'root_dir'", "]", ")", "def_root_dir", "=", "salt", ".", "syspaths", ".", "ROOT_DIR", ".", "rstrip", "(", "os", ...
Prepends the options that represent filesystem paths with value of the 'root_dir' option.
[ "Prepends", "the", "options", "that", "represent", "filesystem", "paths", "with", "value", "of", "the", "root_dir", "option", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2321-L2367
train
saltstack/salt
salt/config/__init__.py
insert_system_path
def insert_system_path(opts, paths): ''' Inserts path into python path taking into consideration 'root_dir' option. ''' if isinstance(paths, six.string_types): paths = [paths] for path in paths: path_options = {'path': path, 'root_dir': opts['root_dir']} prepend_root_dir(path_options, path_options) if (os.path.isdir(path_options['path']) and path_options['path'] not in sys.path): sys.path.insert(0, path_options['path'])
python
def insert_system_path(opts, paths): ''' Inserts path into python path taking into consideration 'root_dir' option. ''' if isinstance(paths, six.string_types): paths = [paths] for path in paths: path_options = {'path': path, 'root_dir': opts['root_dir']} prepend_root_dir(path_options, path_options) if (os.path.isdir(path_options['path']) and path_options['path'] not in sys.path): sys.path.insert(0, path_options['path'])
[ "def", "insert_system_path", "(", "opts", ",", "paths", ")", ":", "if", "isinstance", "(", "paths", ",", "six", ".", "string_types", ")", ":", "paths", "=", "[", "paths", "]", "for", "path", "in", "paths", ":", "path_options", "=", "{", "'path'", ":", ...
Inserts path into python path taking into consideration 'root_dir' option.
[ "Inserts", "path", "into", "python", "path", "taking", "into", "consideration", "root_dir", "option", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2370-L2381
train
saltstack/salt
salt/config/__init__.py
minion_config
def minion_config(path, env_var='SALT_MINION_CONFIG', defaults=None, cache_minion_id=False, ignore_config_errors=True, minion_id=None, role='minion'): ''' Reads in the minion configuration file and sets up special options This is useful for Minion-side operations, such as the :py:class:`~salt.client.Caller` class, and manually running the loader interface. .. code-block:: python import salt.config minion_opts = salt.config.minion_config('/etc/salt/minion') ''' if defaults is None: defaults = DEFAULT_MINION_OPTS.copy() if not os.environ.get(env_var, None): # No valid setting was given using the configuration variable. # Lets see is SALT_CONFIG_DIR is of any use salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None) if salt_config_dir: env_config_file_path = os.path.join(salt_config_dir, 'minion') if salt_config_dir and os.path.isfile(env_config_file_path): # We can get a configuration file using SALT_CONFIG_DIR, let's # update the environment with this information os.environ[env_var] = env_config_file_path overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file']) default_include = overrides.get('default_include', defaults['default_include']) include = overrides.get('include', []) overrides.update(include_config(default_include, path, verbose=False, exit_on_config_errors=not ignore_config_errors)) overrides.update(include_config(include, path, verbose=True, exit_on_config_errors=not ignore_config_errors)) opts = apply_minion_config(overrides, defaults, cache_minion_id=cache_minion_id, minion_id=minion_id) opts['__role'] = role apply_sdb(opts) _validate_opts(opts) return opts
python
def minion_config(path, env_var='SALT_MINION_CONFIG', defaults=None, cache_minion_id=False, ignore_config_errors=True, minion_id=None, role='minion'): ''' Reads in the minion configuration file and sets up special options This is useful for Minion-side operations, such as the :py:class:`~salt.client.Caller` class, and manually running the loader interface. .. code-block:: python import salt.config minion_opts = salt.config.minion_config('/etc/salt/minion') ''' if defaults is None: defaults = DEFAULT_MINION_OPTS.copy() if not os.environ.get(env_var, None): # No valid setting was given using the configuration variable. # Lets see is SALT_CONFIG_DIR is of any use salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None) if salt_config_dir: env_config_file_path = os.path.join(salt_config_dir, 'minion') if salt_config_dir and os.path.isfile(env_config_file_path): # We can get a configuration file using SALT_CONFIG_DIR, let's # update the environment with this information os.environ[env_var] = env_config_file_path overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file']) default_include = overrides.get('default_include', defaults['default_include']) include = overrides.get('include', []) overrides.update(include_config(default_include, path, verbose=False, exit_on_config_errors=not ignore_config_errors)) overrides.update(include_config(include, path, verbose=True, exit_on_config_errors=not ignore_config_errors)) opts = apply_minion_config(overrides, defaults, cache_minion_id=cache_minion_id, minion_id=minion_id) opts['__role'] = role apply_sdb(opts) _validate_opts(opts) return opts
[ "def", "minion_config", "(", "path", ",", "env_var", "=", "'SALT_MINION_CONFIG'", ",", "defaults", "=", "None", ",", "cache_minion_id", "=", "False", ",", "ignore_config_errors", "=", "True", ",", "minion_id", "=", "None", ",", "role", "=", "'minion'", ")", ...
Reads in the minion configuration file and sets up special options This is useful for Minion-side operations, such as the :py:class:`~salt.client.Caller` class, and manually running the loader interface. .. code-block:: python import salt.config minion_opts = salt.config.minion_config('/etc/salt/minion')
[ "Reads", "in", "the", "minion", "configuration", "file", "and", "sets", "up", "special", "options" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2384-L2433
train
saltstack/salt
salt/config/__init__.py
apply_sdb
def apply_sdb(opts, sdb_opts=None): ''' Recurse for sdb:// links for opts ''' # Late load of SDB to keep CLI light import salt.utils.sdb if sdb_opts is None: sdb_opts = opts if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'): return salt.utils.sdb.sdb_get(sdb_opts, opts) elif isinstance(sdb_opts, dict): for key, value in six.iteritems(sdb_opts): if value is None: continue sdb_opts[key] = apply_sdb(opts, value) elif isinstance(sdb_opts, list): for key, value in enumerate(sdb_opts): if value is None: continue sdb_opts[key] = apply_sdb(opts, value) return sdb_opts
python
def apply_sdb(opts, sdb_opts=None): ''' Recurse for sdb:// links for opts ''' # Late load of SDB to keep CLI light import salt.utils.sdb if sdb_opts is None: sdb_opts = opts if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'): return salt.utils.sdb.sdb_get(sdb_opts, opts) elif isinstance(sdb_opts, dict): for key, value in six.iteritems(sdb_opts): if value is None: continue sdb_opts[key] = apply_sdb(opts, value) elif isinstance(sdb_opts, list): for key, value in enumerate(sdb_opts): if value is None: continue sdb_opts[key] = apply_sdb(opts, value) return sdb_opts
[ "def", "apply_sdb", "(", "opts", ",", "sdb_opts", "=", "None", ")", ":", "# Late load of SDB to keep CLI light", "import", "salt", ".", "utils", ".", "sdb", "if", "sdb_opts", "is", "None", ":", "sdb_opts", "=", "opts", "if", "isinstance", "(", "sdb_opts", ",...
Recurse for sdb:// links for opts
[ "Recurse", "for", "sdb", ":", "//", "links", "for", "opts" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2560-L2581
train
saltstack/salt
salt/config/__init__.py
cloud_config
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None, master_config_path=None, master_config=None, providers_config_path=None, providers_config=None, profiles_config_path=None, profiles_config=None): ''' Read in the Salt Cloud config and return the dict ''' if path: config_dir = os.path.dirname(path) else: config_dir = salt.syspaths.CONFIG_DIR # Load the cloud configuration overrides = load_config( path, env_var, os.path.join(config_dir, 'cloud') ) if defaults is None: defaults = DEFAULT_CLOUD_OPTS.copy() # Set defaults early to override Salt Master's default config values later defaults.update(overrides) overrides = defaults # Load cloud configuration from any default or provided includes overrides.update( salt.config.include_config(overrides['default_include'], config_dir, verbose=False) ) include = overrides.get('include', []) overrides.update( salt.config.include_config(include, config_dir, verbose=True) ) # The includes have been evaluated, let's see if master, providers and # profiles configuration settings have been included and if not, set the # default value if 'master_config' in overrides and master_config_path is None: # The configuration setting is being specified in the main cloud # configuration file master_config_path = overrides['master_config'] elif 'master_config' not in overrides and not master_config \ and not master_config_path: # The configuration setting is not being provided in the main cloud # configuration file, and master_config_path = os.path.join(config_dir, 'master') # Convert relative to absolute paths if necessary master_config_path = _absolute_path(master_config_path, config_dir) if 'providers_config' in overrides and providers_config_path is None: # The configuration setting is being specified in the main cloud # configuration file providers_config_path = overrides['providers_config'] elif 'providers_config' not in overrides and not providers_config \ and not providers_config_path: providers_config_path = os.path.join(config_dir, 'cloud.providers') # Convert relative to absolute paths if necessary providers_config_path = _absolute_path(providers_config_path, config_dir) if 'profiles_config' in overrides and profiles_config_path is None: # The configuration setting is being specified in the main cloud # configuration file profiles_config_path = overrides['profiles_config'] elif 'profiles_config' not in overrides and not profiles_config \ and not profiles_config_path: profiles_config_path = os.path.join(config_dir, 'cloud.profiles') # Convert relative to absolute paths if necessary profiles_config_path = _absolute_path(profiles_config_path, config_dir) # Prepare the deploy scripts search path deploy_scripts_search_path = overrides.get( 'deploy_scripts_search_path', defaults.get('deploy_scripts_search_path', 'cloud.deploy.d') ) if isinstance(deploy_scripts_search_path, six.string_types): deploy_scripts_search_path = [deploy_scripts_search_path] # Check the provided deploy scripts search path removing any non existing # entries. for idx, entry in enumerate(deploy_scripts_search_path[:]): if not os.path.isabs(entry): # Let's try adding the provided path's directory name turns the # entry into a proper directory entry = os.path.join(config_dir, entry) if os.path.isdir(entry): # Path exists, let's update the entry (its path might have been # made absolute) deploy_scripts_search_path[idx] = entry continue # It's not a directory? Remove it from the search path deploy_scripts_search_path.pop(idx) # Add the built-in scripts directory to the search path (last resort) deploy_scripts_search_path.append( os.path.abspath( os.path.join( os.path.dirname(__file__), '..', 'cloud', 'deploy' ) ) ) # Let's make the search path a tuple and add it to the overrides. overrides.update( deploy_scripts_search_path=tuple(deploy_scripts_search_path) ) # Grab data from the 4 sources # 1st - Master config if master_config_path is not None and master_config is not None: raise salt.exceptions.SaltCloudConfigError( 'Only pass `master_config` or `master_config_path`, not both.' ) elif master_config_path is None and master_config is None: master_config = salt.config.master_config( overrides.get( # use the value from the cloud config file 'master_config', # if not found, use the default path os.path.join(salt.syspaths.CONFIG_DIR, 'master') ) ) elif master_config_path is not None and master_config is None: master_config = salt.config.master_config(master_config_path) # cloud config has a separate cachedir del master_config['cachedir'] # 2nd - salt-cloud configuration which was loaded before so we could # extract the master configuration file if needed. # Override master configuration with the salt cloud(current overrides) master_config.update(overrides) # We now set the overridden master_config as the overrides overrides = master_config if providers_config_path is not None and providers_config is not None: raise salt.exceptions.SaltCloudConfigError( 'Only pass `providers_config` or `providers_config_path`, ' 'not both.' ) elif providers_config_path is None and providers_config is None: providers_config_path = overrides.get( # use the value from the cloud config file 'providers_config', # if not found, use the default path os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers') ) if profiles_config_path is not None and profiles_config is not None: raise salt.exceptions.SaltCloudConfigError( 'Only pass `profiles_config` or `profiles_config_path`, not both.' ) elif profiles_config_path is None and profiles_config is None: profiles_config_path = overrides.get( # use the value from the cloud config file 'profiles_config', # if not found, use the default path os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles') ) # Apply the salt-cloud configuration opts = apply_cloud_config(overrides, defaults) # 3rd - Include Cloud Providers if 'providers' in opts: if providers_config is not None: raise salt.exceptions.SaltCloudConfigError( 'Do not mix the old cloud providers configuration with ' 'the passing a pre-configured providers configuration ' 'dictionary.' ) if providers_config_path is not None: providers_confd = os.path.join( os.path.dirname(providers_config_path), 'cloud.providers.d', '*' ) if (os.path.isfile(providers_config_path) or glob.glob(providers_confd)): raise salt.exceptions.SaltCloudConfigError( 'Do not mix the old cloud providers configuration with ' 'the new one. The providers configuration should now go ' 'in the file `{0}` or a separate `*.conf` file within ' '`cloud.providers.d/` which is relative to `{0}`.'.format( os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers') ) ) # No exception was raised? It's the old configuration alone providers_config = opts['providers'] elif providers_config_path is not None: # Load from configuration file, even if that files does not exist since # it will be populated with defaults. providers_config = cloud_providers_config(providers_config_path) # Let's assign back the computed providers configuration opts['providers'] = providers_config # 4th - Include VM profiles config if profiles_config is None: # Load profiles configuration from the provided file profiles_config = vm_profiles_config(profiles_config_path, providers_config) opts['profiles'] = profiles_config # recurse opts for sdb configs apply_sdb(opts) # prepend root_dir prepend_root_dirs = ['cachedir'] if 'log_file' in opts and urlparse(opts['log_file']).scheme == '': prepend_root_dirs.append(opts['log_file']) prepend_root_dir(opts, prepend_root_dirs) # Return the final options return opts
python
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None, master_config_path=None, master_config=None, providers_config_path=None, providers_config=None, profiles_config_path=None, profiles_config=None): ''' Read in the Salt Cloud config and return the dict ''' if path: config_dir = os.path.dirname(path) else: config_dir = salt.syspaths.CONFIG_DIR # Load the cloud configuration overrides = load_config( path, env_var, os.path.join(config_dir, 'cloud') ) if defaults is None: defaults = DEFAULT_CLOUD_OPTS.copy() # Set defaults early to override Salt Master's default config values later defaults.update(overrides) overrides = defaults # Load cloud configuration from any default or provided includes overrides.update( salt.config.include_config(overrides['default_include'], config_dir, verbose=False) ) include = overrides.get('include', []) overrides.update( salt.config.include_config(include, config_dir, verbose=True) ) # The includes have been evaluated, let's see if master, providers and # profiles configuration settings have been included and if not, set the # default value if 'master_config' in overrides and master_config_path is None: # The configuration setting is being specified in the main cloud # configuration file master_config_path = overrides['master_config'] elif 'master_config' not in overrides and not master_config \ and not master_config_path: # The configuration setting is not being provided in the main cloud # configuration file, and master_config_path = os.path.join(config_dir, 'master') # Convert relative to absolute paths if necessary master_config_path = _absolute_path(master_config_path, config_dir) if 'providers_config' in overrides and providers_config_path is None: # The configuration setting is being specified in the main cloud # configuration file providers_config_path = overrides['providers_config'] elif 'providers_config' not in overrides and not providers_config \ and not providers_config_path: providers_config_path = os.path.join(config_dir, 'cloud.providers') # Convert relative to absolute paths if necessary providers_config_path = _absolute_path(providers_config_path, config_dir) if 'profiles_config' in overrides and profiles_config_path is None: # The configuration setting is being specified in the main cloud # configuration file profiles_config_path = overrides['profiles_config'] elif 'profiles_config' not in overrides and not profiles_config \ and not profiles_config_path: profiles_config_path = os.path.join(config_dir, 'cloud.profiles') # Convert relative to absolute paths if necessary profiles_config_path = _absolute_path(profiles_config_path, config_dir) # Prepare the deploy scripts search path deploy_scripts_search_path = overrides.get( 'deploy_scripts_search_path', defaults.get('deploy_scripts_search_path', 'cloud.deploy.d') ) if isinstance(deploy_scripts_search_path, six.string_types): deploy_scripts_search_path = [deploy_scripts_search_path] # Check the provided deploy scripts search path removing any non existing # entries. for idx, entry in enumerate(deploy_scripts_search_path[:]): if not os.path.isabs(entry): # Let's try adding the provided path's directory name turns the # entry into a proper directory entry = os.path.join(config_dir, entry) if os.path.isdir(entry): # Path exists, let's update the entry (its path might have been # made absolute) deploy_scripts_search_path[idx] = entry continue # It's not a directory? Remove it from the search path deploy_scripts_search_path.pop(idx) # Add the built-in scripts directory to the search path (last resort) deploy_scripts_search_path.append( os.path.abspath( os.path.join( os.path.dirname(__file__), '..', 'cloud', 'deploy' ) ) ) # Let's make the search path a tuple and add it to the overrides. overrides.update( deploy_scripts_search_path=tuple(deploy_scripts_search_path) ) # Grab data from the 4 sources # 1st - Master config if master_config_path is not None and master_config is not None: raise salt.exceptions.SaltCloudConfigError( 'Only pass `master_config` or `master_config_path`, not both.' ) elif master_config_path is None and master_config is None: master_config = salt.config.master_config( overrides.get( # use the value from the cloud config file 'master_config', # if not found, use the default path os.path.join(salt.syspaths.CONFIG_DIR, 'master') ) ) elif master_config_path is not None and master_config is None: master_config = salt.config.master_config(master_config_path) # cloud config has a separate cachedir del master_config['cachedir'] # 2nd - salt-cloud configuration which was loaded before so we could # extract the master configuration file if needed. # Override master configuration with the salt cloud(current overrides) master_config.update(overrides) # We now set the overridden master_config as the overrides overrides = master_config if providers_config_path is not None and providers_config is not None: raise salt.exceptions.SaltCloudConfigError( 'Only pass `providers_config` or `providers_config_path`, ' 'not both.' ) elif providers_config_path is None and providers_config is None: providers_config_path = overrides.get( # use the value from the cloud config file 'providers_config', # if not found, use the default path os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers') ) if profiles_config_path is not None and profiles_config is not None: raise salt.exceptions.SaltCloudConfigError( 'Only pass `profiles_config` or `profiles_config_path`, not both.' ) elif profiles_config_path is None and profiles_config is None: profiles_config_path = overrides.get( # use the value from the cloud config file 'profiles_config', # if not found, use the default path os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles') ) # Apply the salt-cloud configuration opts = apply_cloud_config(overrides, defaults) # 3rd - Include Cloud Providers if 'providers' in opts: if providers_config is not None: raise salt.exceptions.SaltCloudConfigError( 'Do not mix the old cloud providers configuration with ' 'the passing a pre-configured providers configuration ' 'dictionary.' ) if providers_config_path is not None: providers_confd = os.path.join( os.path.dirname(providers_config_path), 'cloud.providers.d', '*' ) if (os.path.isfile(providers_config_path) or glob.glob(providers_confd)): raise salt.exceptions.SaltCloudConfigError( 'Do not mix the old cloud providers configuration with ' 'the new one. The providers configuration should now go ' 'in the file `{0}` or a separate `*.conf` file within ' '`cloud.providers.d/` which is relative to `{0}`.'.format( os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers') ) ) # No exception was raised? It's the old configuration alone providers_config = opts['providers'] elif providers_config_path is not None: # Load from configuration file, even if that files does not exist since # it will be populated with defaults. providers_config = cloud_providers_config(providers_config_path) # Let's assign back the computed providers configuration opts['providers'] = providers_config # 4th - Include VM profiles config if profiles_config is None: # Load profiles configuration from the provided file profiles_config = vm_profiles_config(profiles_config_path, providers_config) opts['profiles'] = profiles_config # recurse opts for sdb configs apply_sdb(opts) # prepend root_dir prepend_root_dirs = ['cachedir'] if 'log_file' in opts and urlparse(opts['log_file']).scheme == '': prepend_root_dirs.append(opts['log_file']) prepend_root_dir(opts, prepend_root_dirs) # Return the final options return opts
[ "def", "cloud_config", "(", "path", "=", "None", ",", "env_var", "=", "'SALT_CLOUD_CONFIG'", ",", "defaults", "=", "None", ",", "master_config_path", "=", "None", ",", "master_config", "=", "None", ",", "providers_config_path", "=", "None", ",", "providers_confi...
Read in the Salt Cloud config and return the dict
[ "Read", "in", "the", "Salt", "Cloud", "config", "and", "return", "the", "dict" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2585-L2810
train
saltstack/salt
salt/config/__init__.py
apply_cloud_config
def apply_cloud_config(overrides, defaults=None): ''' Return a cloud config ''' if defaults is None: defaults = DEFAULT_CLOUD_OPTS.copy() config = defaults.copy() if overrides: config.update(overrides) # If the user defined providers in salt cloud's main configuration file, we # need to take care for proper and expected format. if 'providers' in config: # Keep a copy of the defined providers providers = config['providers'].copy() # Reset the providers dictionary config['providers'] = {} # Populate the providers dictionary for alias, details in six.iteritems(providers): if isinstance(details, list): for detail in details: if 'driver' not in detail: raise salt.exceptions.SaltCloudConfigError( 'The cloud provider alias \'{0}\' has an entry ' 'missing the required setting of \'driver\'.'.format( alias ) ) driver = detail['driver'] if ':' in driver: # Weird, but... alias, driver = driver.split(':') if alias not in config['providers']: config['providers'][alias] = {} detail['provider'] = '{0}:{1}'.format(alias, driver) config['providers'][alias][driver] = detail elif isinstance(details, dict): if 'driver' not in details: raise salt.exceptions.SaltCloudConfigError( 'The cloud provider alias \'{0}\' has an entry ' 'missing the required setting of \'driver\''.format( alias ) ) driver = details['driver'] if ':' in driver: # Weird, but... alias, driver = driver.split(':') if alias not in config['providers']: config['providers'][alias] = {} details['provider'] = '{0}:{1}'.format(alias, driver) config['providers'][alias][driver] = details # Migrate old configuration config = old_to_new(config) return config
python
def apply_cloud_config(overrides, defaults=None): ''' Return a cloud config ''' if defaults is None: defaults = DEFAULT_CLOUD_OPTS.copy() config = defaults.copy() if overrides: config.update(overrides) # If the user defined providers in salt cloud's main configuration file, we # need to take care for proper and expected format. if 'providers' in config: # Keep a copy of the defined providers providers = config['providers'].copy() # Reset the providers dictionary config['providers'] = {} # Populate the providers dictionary for alias, details in six.iteritems(providers): if isinstance(details, list): for detail in details: if 'driver' not in detail: raise salt.exceptions.SaltCloudConfigError( 'The cloud provider alias \'{0}\' has an entry ' 'missing the required setting of \'driver\'.'.format( alias ) ) driver = detail['driver'] if ':' in driver: # Weird, but... alias, driver = driver.split(':') if alias not in config['providers']: config['providers'][alias] = {} detail['provider'] = '{0}:{1}'.format(alias, driver) config['providers'][alias][driver] = detail elif isinstance(details, dict): if 'driver' not in details: raise salt.exceptions.SaltCloudConfigError( 'The cloud provider alias \'{0}\' has an entry ' 'missing the required setting of \'driver\''.format( alias ) ) driver = details['driver'] if ':' in driver: # Weird, but... alias, driver = driver.split(':') if alias not in config['providers']: config['providers'][alias] = {} details['provider'] = '{0}:{1}'.format(alias, driver) config['providers'][alias][driver] = details # Migrate old configuration config = old_to_new(config) return config
[ "def", "apply_cloud_config", "(", "overrides", ",", "defaults", "=", "None", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "DEFAULT_CLOUD_OPTS", ".", "copy", "(", ")", "config", "=", "defaults", ".", "copy", "(", ")", "if", "overrides", ...
Return a cloud config
[ "Return", "a", "cloud", "config" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2813-L2877
train
saltstack/salt
salt/config/__init__.py
vm_profiles_config
def vm_profiles_config(path, providers, env_var='SALT_CLOUDVM_CONFIG', defaults=None): ''' Read in the salt cloud VM config file ''' if defaults is None: defaults = VM_CONFIG_DEFAULTS overrides = salt.config.load_config( path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles') ) default_include = overrides.get( 'default_include', defaults['default_include'] ) include = overrides.get('include', []) overrides.update( salt.config.include_config(default_include, path, verbose=False) ) overrides.update( salt.config.include_config(include, path, verbose=True) ) return apply_vm_profiles_config(providers, overrides, defaults)
python
def vm_profiles_config(path, providers, env_var='SALT_CLOUDVM_CONFIG', defaults=None): ''' Read in the salt cloud VM config file ''' if defaults is None: defaults = VM_CONFIG_DEFAULTS overrides = salt.config.load_config( path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles') ) default_include = overrides.get( 'default_include', defaults['default_include'] ) include = overrides.get('include', []) overrides.update( salt.config.include_config(default_include, path, verbose=False) ) overrides.update( salt.config.include_config(include, path, verbose=True) ) return apply_vm_profiles_config(providers, overrides, defaults)
[ "def", "vm_profiles_config", "(", "path", ",", "providers", ",", "env_var", "=", "'SALT_CLOUDVM_CONFIG'", ",", "defaults", "=", "None", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "VM_CONFIG_DEFAULTS", "overrides", "=", "salt", ".", "config...
Read in the salt cloud VM config file
[ "Read", "in", "the", "salt", "cloud", "VM", "config", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2916-L2941
train
saltstack/salt
salt/config/__init__.py
cloud_providers_config
def cloud_providers_config(path, env_var='SALT_CLOUD_PROVIDERS_CONFIG', defaults=None): ''' Read in the salt cloud providers configuration file ''' if defaults is None: defaults = PROVIDER_CONFIG_DEFAULTS overrides = salt.config.load_config( path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers') ) default_include = overrides.get( 'default_include', defaults['default_include'] ) include = overrides.get('include', []) overrides.update( salt.config.include_config(default_include, path, verbose=False) ) overrides.update( salt.config.include_config(include, path, verbose=True) ) return apply_cloud_providers_config(overrides, defaults)
python
def cloud_providers_config(path, env_var='SALT_CLOUD_PROVIDERS_CONFIG', defaults=None): ''' Read in the salt cloud providers configuration file ''' if defaults is None: defaults = PROVIDER_CONFIG_DEFAULTS overrides = salt.config.load_config( path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers') ) default_include = overrides.get( 'default_include', defaults['default_include'] ) include = overrides.get('include', []) overrides.update( salt.config.include_config(default_include, path, verbose=False) ) overrides.update( salt.config.include_config(include, path, verbose=True) ) return apply_cloud_providers_config(overrides, defaults)
[ "def", "cloud_providers_config", "(", "path", ",", "env_var", "=", "'SALT_CLOUD_PROVIDERS_CONFIG'", ",", "defaults", "=", "None", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "PROVIDER_CONFIG_DEFAULTS", "overrides", "=", "salt", ".", "config", ...
Read in the salt cloud providers configuration file
[ "Read", "in", "the", "salt", "cloud", "providers", "configuration", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3057-L3081
train
saltstack/salt
salt/config/__init__.py
apply_cloud_providers_config
def apply_cloud_providers_config(overrides, defaults=None): ''' Apply the loaded cloud providers configuration. ''' if defaults is None: defaults = PROVIDER_CONFIG_DEFAULTS config = defaults.copy() if overrides: config.update(overrides) # Is the user still using the old format in the new configuration file?! for name, settings in six.iteritems(config.copy()): if '.' in name: log.warning( 'Please switch to the new providers configuration syntax' ) # Let's help out and migrate the data config = old_to_new(config) # old_to_new will migrate the old data into the 'providers' key of # the config dictionary. Let's map it correctly for prov_name, prov_settings in six.iteritems(config.pop('providers')): config[prov_name] = prov_settings break providers = {} ext_count = 0 for key, val in six.iteritems(config): if key in ('conf_file', 'include', 'default_include', 'user'): continue if not isinstance(val, (list, tuple)): val = [val] else: # Need to check for duplicate cloud provider entries per "alias" or # we won't be able to properly reference it. handled_providers = set() for details in val: if 'driver' not in details: if 'extends' not in details: log.error( 'Please check your cloud providers configuration. ' 'There\'s no \'driver\' nor \'extends\' definition ' 'referenced.' ) continue if details['driver'] in handled_providers: log.error( 'You can only have one entry per cloud provider. For ' 'example, if you have a cloud provider configuration ' 'section named, \'production\', you can only have a ' 'single entry for EC2, Joyent, Openstack, and so ' 'forth.' ) raise salt.exceptions.SaltCloudConfigError( 'The cloud provider alias \'{0}\' has multiple entries ' 'for the \'{1[driver]}\' driver.'.format(key, details) ) handled_providers.add(details['driver']) for entry in val: if 'driver' not in entry: entry['driver'] = '-only-extendable-{0}'.format(ext_count) ext_count += 1 if key not in providers: providers[key] = {} provider = entry['driver'] if provider not in providers[key]: providers[key][provider] = entry # Is any provider extending data!? while True: keep_looping = False for provider_alias, entries in six.iteritems(providers.copy()): for driver, details in six.iteritems(entries): # Set a holder for the defined profiles providers[provider_alias][driver]['profiles'] = {} if 'extends' not in details: continue extends = details.pop('extends') if ':' in extends: alias, provider = extends.split(':') if alias not in providers: raise salt.exceptions.SaltCloudConfigError( 'The \'{0}\' cloud provider entry in \'{1}\' is ' 'trying to extend data from \'{2}\' though ' '\'{2}\' is not defined in the salt cloud ' 'providers loaded data.'.format( details['driver'], provider_alias, alias ) ) if provider not in providers.get(alias): raise salt.exceptions.SaltCloudConfigError( 'The \'{0}\' cloud provider entry in \'{1}\' is ' 'trying to extend data from \'{2}:{3}\' though ' '\'{3}\' is not defined in \'{1}\''.format( details['driver'], provider_alias, alias, provider ) ) details['extends'] = '{0}:{1}'.format(alias, provider) # change provider details '-only-extendable-' to extended # provider name details['driver'] = provider elif providers.get(extends): raise salt.exceptions.SaltCloudConfigError( 'The \'{0}\' cloud provider entry in \'{1}\' is ' 'trying to extend from \'{2}\' and no provider was ' 'specified. Not extending!'.format( details['driver'], provider_alias, extends ) ) elif extends not in providers: raise salt.exceptions.SaltCloudConfigError( 'The \'{0}\' cloud provider entry in \'{1}\' is ' 'trying to extend data from \'{2}\' though \'{2}\' ' 'is not defined in the salt cloud providers loaded ' 'data.'.format( details['driver'], provider_alias, extends ) ) else: if driver in providers.get(extends): details['extends'] = '{0}:{1}'.format(extends, driver) elif '-only-extendable-' in providers.get(extends): details['extends'] = '{0}:{1}'.format( extends, '-only-extendable-{0}'.format(ext_count) ) else: # We're still not aware of what we're trying to extend # from. Let's try on next iteration details['extends'] = extends keep_looping = True if not keep_looping: break while True: # Merge provided extends keep_looping = False for alias, entries in six.iteritems(providers.copy()): for driver, details in six.iteritems(entries): if 'extends' not in details: # Extends resolved or non existing, continue! continue if 'extends' in details['extends']: # Since there's a nested extends, resolve this one in the # next iteration keep_looping = True continue # Let's get a reference to what we're supposed to extend extends = details.pop('extends') # Split the setting in (alias, driver) ext_alias, ext_driver = extends.split(':') # Grab a copy of what should be extended extended = providers.get(ext_alias).get(ext_driver).copy() # Merge the data to extend with the details extended = salt.utils.dictupdate.update(extended, details) # Update the providers dictionary with the merged data providers[alias][driver] = extended # Update name of the driver, now that it's populated with extended information if driver.startswith('-only-extendable-'): providers[alias][ext_driver] = providers[alias][driver] # Delete driver with old name to maintain dictionary size del providers[alias][driver] if not keep_looping: break # Now clean up any providers entry that was just used to be a data tree to # extend from for provider_alias, entries in six.iteritems(providers.copy()): for driver, details in six.iteritems(entries.copy()): if not driver.startswith('-only-extendable-'): continue log.info( "There's at least one cloud driver under the '%s' " 'cloud provider alias which does not have the required ' "'driver' setting. Removing it from the available " 'providers listing.', provider_alias ) providers[provider_alias].pop(driver) if not providers[provider_alias]: providers.pop(provider_alias) return providers
python
def apply_cloud_providers_config(overrides, defaults=None): ''' Apply the loaded cloud providers configuration. ''' if defaults is None: defaults = PROVIDER_CONFIG_DEFAULTS config = defaults.copy() if overrides: config.update(overrides) # Is the user still using the old format in the new configuration file?! for name, settings in six.iteritems(config.copy()): if '.' in name: log.warning( 'Please switch to the new providers configuration syntax' ) # Let's help out and migrate the data config = old_to_new(config) # old_to_new will migrate the old data into the 'providers' key of # the config dictionary. Let's map it correctly for prov_name, prov_settings in six.iteritems(config.pop('providers')): config[prov_name] = prov_settings break providers = {} ext_count = 0 for key, val in six.iteritems(config): if key in ('conf_file', 'include', 'default_include', 'user'): continue if not isinstance(val, (list, tuple)): val = [val] else: # Need to check for duplicate cloud provider entries per "alias" or # we won't be able to properly reference it. handled_providers = set() for details in val: if 'driver' not in details: if 'extends' not in details: log.error( 'Please check your cloud providers configuration. ' 'There\'s no \'driver\' nor \'extends\' definition ' 'referenced.' ) continue if details['driver'] in handled_providers: log.error( 'You can only have one entry per cloud provider. For ' 'example, if you have a cloud provider configuration ' 'section named, \'production\', you can only have a ' 'single entry for EC2, Joyent, Openstack, and so ' 'forth.' ) raise salt.exceptions.SaltCloudConfigError( 'The cloud provider alias \'{0}\' has multiple entries ' 'for the \'{1[driver]}\' driver.'.format(key, details) ) handled_providers.add(details['driver']) for entry in val: if 'driver' not in entry: entry['driver'] = '-only-extendable-{0}'.format(ext_count) ext_count += 1 if key not in providers: providers[key] = {} provider = entry['driver'] if provider not in providers[key]: providers[key][provider] = entry # Is any provider extending data!? while True: keep_looping = False for provider_alias, entries in six.iteritems(providers.copy()): for driver, details in six.iteritems(entries): # Set a holder for the defined profiles providers[provider_alias][driver]['profiles'] = {} if 'extends' not in details: continue extends = details.pop('extends') if ':' in extends: alias, provider = extends.split(':') if alias not in providers: raise salt.exceptions.SaltCloudConfigError( 'The \'{0}\' cloud provider entry in \'{1}\' is ' 'trying to extend data from \'{2}\' though ' '\'{2}\' is not defined in the salt cloud ' 'providers loaded data.'.format( details['driver'], provider_alias, alias ) ) if provider not in providers.get(alias): raise salt.exceptions.SaltCloudConfigError( 'The \'{0}\' cloud provider entry in \'{1}\' is ' 'trying to extend data from \'{2}:{3}\' though ' '\'{3}\' is not defined in \'{1}\''.format( details['driver'], provider_alias, alias, provider ) ) details['extends'] = '{0}:{1}'.format(alias, provider) # change provider details '-only-extendable-' to extended # provider name details['driver'] = provider elif providers.get(extends): raise salt.exceptions.SaltCloudConfigError( 'The \'{0}\' cloud provider entry in \'{1}\' is ' 'trying to extend from \'{2}\' and no provider was ' 'specified. Not extending!'.format( details['driver'], provider_alias, extends ) ) elif extends not in providers: raise salt.exceptions.SaltCloudConfigError( 'The \'{0}\' cloud provider entry in \'{1}\' is ' 'trying to extend data from \'{2}\' though \'{2}\' ' 'is not defined in the salt cloud providers loaded ' 'data.'.format( details['driver'], provider_alias, extends ) ) else: if driver in providers.get(extends): details['extends'] = '{0}:{1}'.format(extends, driver) elif '-only-extendable-' in providers.get(extends): details['extends'] = '{0}:{1}'.format( extends, '-only-extendable-{0}'.format(ext_count) ) else: # We're still not aware of what we're trying to extend # from. Let's try on next iteration details['extends'] = extends keep_looping = True if not keep_looping: break while True: # Merge provided extends keep_looping = False for alias, entries in six.iteritems(providers.copy()): for driver, details in six.iteritems(entries): if 'extends' not in details: # Extends resolved or non existing, continue! continue if 'extends' in details['extends']: # Since there's a nested extends, resolve this one in the # next iteration keep_looping = True continue # Let's get a reference to what we're supposed to extend extends = details.pop('extends') # Split the setting in (alias, driver) ext_alias, ext_driver = extends.split(':') # Grab a copy of what should be extended extended = providers.get(ext_alias).get(ext_driver).copy() # Merge the data to extend with the details extended = salt.utils.dictupdate.update(extended, details) # Update the providers dictionary with the merged data providers[alias][driver] = extended # Update name of the driver, now that it's populated with extended information if driver.startswith('-only-extendable-'): providers[alias][ext_driver] = providers[alias][driver] # Delete driver with old name to maintain dictionary size del providers[alias][driver] if not keep_looping: break # Now clean up any providers entry that was just used to be a data tree to # extend from for provider_alias, entries in six.iteritems(providers.copy()): for driver, details in six.iteritems(entries.copy()): if not driver.startswith('-only-extendable-'): continue log.info( "There's at least one cloud driver under the '%s' " 'cloud provider alias which does not have the required ' "'driver' setting. Removing it from the available " 'providers listing.', provider_alias ) providers[provider_alias].pop(driver) if not providers[provider_alias]: providers.pop(provider_alias) return providers
[ "def", "apply_cloud_providers_config", "(", "overrides", ",", "defaults", "=", "None", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "PROVIDER_CONFIG_DEFAULTS", "config", "=", "defaults", ".", "copy", "(", ")", "if", "overrides", ":", "config...
Apply the loaded cloud providers configuration.
[ "Apply", "the", "loaded", "cloud", "providers", "configuration", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3084-L3287
train
saltstack/salt
salt/config/__init__.py
get_cloud_config_value
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True): ''' Search and return a setting in a known order: 1. In the virtual machine's configuration 2. In the virtual machine's profile configuration 3. In the virtual machine's provider configuration 4. In the salt cloud configuration if global searching is enabled 5. Return the provided default ''' # As a last resort, return the default value = default if search_global is True and opts.get(name, None) is not None: # The setting name exists in the cloud(global) configuration value = deepcopy(opts[name]) if vm_ and name: # Let's get the value from the profile, if present if 'profile' in vm_ and vm_['profile'] is not None: if name in opts['profiles'][vm_['profile']]: if isinstance(value, dict): value.update(opts['profiles'][vm_['profile']][name].copy()) else: value = deepcopy(opts['profiles'][vm_['profile']][name]) # Let's get the value from the provider, if present. if ':' in vm_['driver']: # The provider is defined as <provider-alias>:<driver-name> alias, driver = vm_['driver'].split(':') if alias in opts['providers'] and \ driver in opts['providers'][alias]: details = opts['providers'][alias][driver] if name in details: if isinstance(value, dict): value.update(details[name].copy()) else: value = deepcopy(details[name]) elif len(opts['providers'].get(vm_['driver'], ())) > 1: # The provider is NOT defined as <provider-alias>:<driver-name> # and there's more than one entry under the alias. # WARN the user!!!! log.error( "The '%s' cloud provider definition has more than one " 'entry. Your VM configuration should be specifying the ' "provider as 'driver: %s:<driver-engine>'. Since " "it's not, we're returning the first definition which " 'might not be what you intended.', vm_['driver'], vm_['driver'] ) if vm_['driver'] in opts['providers']: # There's only one driver defined for this provider. This is safe. alias_defs = opts['providers'].get(vm_['driver']) provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))] if name in provider_driver_defs: # The setting name exists in the VM's provider configuration. # Return it! if isinstance(value, dict): value.update(provider_driver_defs[name].copy()) else: value = deepcopy(provider_driver_defs[name]) if name and vm_ and name in vm_: # The setting name exists in VM configuration. if isinstance(vm_[name], types.GeneratorType): value = next(vm_[name], '') else: if isinstance(value, dict) and isinstance(vm_[name], dict): value.update(vm_[name].copy()) else: value = deepcopy(vm_[name]) return value
python
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True): ''' Search and return a setting in a known order: 1. In the virtual machine's configuration 2. In the virtual machine's profile configuration 3. In the virtual machine's provider configuration 4. In the salt cloud configuration if global searching is enabled 5. Return the provided default ''' # As a last resort, return the default value = default if search_global is True and opts.get(name, None) is not None: # The setting name exists in the cloud(global) configuration value = deepcopy(opts[name]) if vm_ and name: # Let's get the value from the profile, if present if 'profile' in vm_ and vm_['profile'] is not None: if name in opts['profiles'][vm_['profile']]: if isinstance(value, dict): value.update(opts['profiles'][vm_['profile']][name].copy()) else: value = deepcopy(opts['profiles'][vm_['profile']][name]) # Let's get the value from the provider, if present. if ':' in vm_['driver']: # The provider is defined as <provider-alias>:<driver-name> alias, driver = vm_['driver'].split(':') if alias in opts['providers'] and \ driver in opts['providers'][alias]: details = opts['providers'][alias][driver] if name in details: if isinstance(value, dict): value.update(details[name].copy()) else: value = deepcopy(details[name]) elif len(opts['providers'].get(vm_['driver'], ())) > 1: # The provider is NOT defined as <provider-alias>:<driver-name> # and there's more than one entry under the alias. # WARN the user!!!! log.error( "The '%s' cloud provider definition has more than one " 'entry. Your VM configuration should be specifying the ' "provider as 'driver: %s:<driver-engine>'. Since " "it's not, we're returning the first definition which " 'might not be what you intended.', vm_['driver'], vm_['driver'] ) if vm_['driver'] in opts['providers']: # There's only one driver defined for this provider. This is safe. alias_defs = opts['providers'].get(vm_['driver']) provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))] if name in provider_driver_defs: # The setting name exists in the VM's provider configuration. # Return it! if isinstance(value, dict): value.update(provider_driver_defs[name].copy()) else: value = deepcopy(provider_driver_defs[name]) if name and vm_ and name in vm_: # The setting name exists in VM configuration. if isinstance(vm_[name], types.GeneratorType): value = next(vm_[name], '') else: if isinstance(value, dict) and isinstance(vm_[name], dict): value.update(vm_[name].copy()) else: value = deepcopy(vm_[name]) return value
[ "def", "get_cloud_config_value", "(", "name", ",", "vm_", ",", "opts", ",", "default", "=", "None", ",", "search_global", "=", "True", ")", ":", "# As a last resort, return the default", "value", "=", "default", "if", "search_global", "is", "True", "and", "opts"...
Search and return a setting in a known order: 1. In the virtual machine's configuration 2. In the virtual machine's profile configuration 3. In the virtual machine's provider configuration 4. In the salt cloud configuration if global searching is enabled 5. Return the provided default
[ "Search", "and", "return", "a", "setting", "in", "a", "known", "order", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3290-L3364
train
saltstack/salt
salt/config/__init__.py
is_provider_configured
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()): ''' Check and return the first matching and fully configured cloud provider configuration. ''' if ':' in provider: alias, driver = provider.split(':') if alias not in opts['providers']: return False if driver not in opts['providers'][alias]: return False for key in required_keys: if opts['providers'][alias][driver].get(key, None) is None: if log_message is True: # There's at least one require configuration key which is not # set. log.warning( "The required '%s' configuration setting is missing " "from the '%s' driver, which is configured under the " "'%s' alias.", key, provider, alias ) return False # If we reached this far, there's a properly configured provider. # Return it! return opts['providers'][alias][driver] for alias, drivers in six.iteritems(opts['providers']): for driver, provider_details in six.iteritems(drivers): if driver != provider and driver not in aliases: continue # If we reached this far, we have a matching provider, let's see if # all required configuration keys are present and not None. skip_provider = False for key in required_keys: if provider_details.get(key, None) is None: if log_message is True: # This provider does not include all necessary keys, # continue to next one. log.warning( "The required '%s' configuration setting is " "missing from the '%s' driver, which is configured " "under the '%s' alias.", key, provider, alias ) skip_provider = True break if skip_provider: continue # If we reached this far, the provider included all required keys return provider_details # If we reached this point, the provider is not configured. return False
python
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()): ''' Check and return the first matching and fully configured cloud provider configuration. ''' if ':' in provider: alias, driver = provider.split(':') if alias not in opts['providers']: return False if driver not in opts['providers'][alias]: return False for key in required_keys: if opts['providers'][alias][driver].get(key, None) is None: if log_message is True: # There's at least one require configuration key which is not # set. log.warning( "The required '%s' configuration setting is missing " "from the '%s' driver, which is configured under the " "'%s' alias.", key, provider, alias ) return False # If we reached this far, there's a properly configured provider. # Return it! return opts['providers'][alias][driver] for alias, drivers in six.iteritems(opts['providers']): for driver, provider_details in six.iteritems(drivers): if driver != provider and driver not in aliases: continue # If we reached this far, we have a matching provider, let's see if # all required configuration keys are present and not None. skip_provider = False for key in required_keys: if provider_details.get(key, None) is None: if log_message is True: # This provider does not include all necessary keys, # continue to next one. log.warning( "The required '%s' configuration setting is " "missing from the '%s' driver, which is configured " "under the '%s' alias.", key, provider, alias ) skip_provider = True break if skip_provider: continue # If we reached this far, the provider included all required keys return provider_details # If we reached this point, the provider is not configured. return False
[ "def", "is_provider_configured", "(", "opts", ",", "provider", ",", "required_keys", "=", "(", ")", ",", "log_message", "=", "True", ",", "aliases", "=", "(", ")", ")", ":", "if", "':'", "in", "provider", ":", "alias", ",", "driver", "=", "provider", "...
Check and return the first matching and fully configured cloud provider configuration.
[ "Check", "and", "return", "the", "first", "matching", "and", "fully", "configured", "cloud", "provider", "configuration", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3367-L3421
train
saltstack/salt
salt/config/__init__.py
is_profile_configured
def is_profile_configured(opts, provider, profile_name, vm_=None): ''' Check if the requested profile contains the minimum required parameters for a profile. Required parameters include image and provider for all drivers, while some drivers also require size keys. .. versionadded:: 2015.8.0 ''' # Standard dict keys required by all drivers. required_keys = ['provider'] alias, driver = provider.split(':') # Most drivers need an image to be specified, but some do not. non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks'] # Most drivers need a size, but some do not. non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway', 'softlayer', 'softlayer_hw', 'vmware', 'vsphere', 'virtualbox', 'libvirt', 'oneandone', 'profitbricks'] provider_key = opts['providers'][alias][driver] profile_key = opts['providers'][alias][driver]['profiles'][profile_name] # If cloning on Linode, size and image are not necessary. # They are obtained from the to-be-cloned VM. if driver == 'linode' and profile_key.get('clonefrom', False): non_image_drivers.append('linode') non_size_drivers.append('linode') elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')): non_image_drivers.append('gce') # If cloning on VMware, specifying image is not necessary. if driver == 'vmware' and 'image' not in list(profile_key.keys()): non_image_drivers.append('vmware') if driver not in non_image_drivers: required_keys.append('image') if driver == 'vmware': required_keys.append('datastore') elif driver in ['linode', 'virtualbox']: required_keys.append('clonefrom') elif driver == 'nova': nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume'] if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]): required_keys.extend(nova_image_keys) if driver not in non_size_drivers: required_keys.append('size') # Check if required fields are supplied in the provider config. If they # are present, remove it from the required_keys list. for item in list(required_keys): if item in provider_key: required_keys.remove(item) # If a vm_ dict was passed in, use that information to get any other configs # that we might have missed thus far, such as a option provided in a map file. if vm_: for item in list(required_keys): if item in vm_: required_keys.remove(item) # Check for remaining required parameters in the profile config. for item in required_keys: if profile_key.get(item, None) is None: # There's at least one required configuration item which is not set. log.error( "The required '%s' configuration setting is missing from " "the '%s' profile, which is configured under the '%s' alias.", item, profile_name, alias ) return False return True
python
def is_profile_configured(opts, provider, profile_name, vm_=None): ''' Check if the requested profile contains the minimum required parameters for a profile. Required parameters include image and provider for all drivers, while some drivers also require size keys. .. versionadded:: 2015.8.0 ''' # Standard dict keys required by all drivers. required_keys = ['provider'] alias, driver = provider.split(':') # Most drivers need an image to be specified, but some do not. non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks'] # Most drivers need a size, but some do not. non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway', 'softlayer', 'softlayer_hw', 'vmware', 'vsphere', 'virtualbox', 'libvirt', 'oneandone', 'profitbricks'] provider_key = opts['providers'][alias][driver] profile_key = opts['providers'][alias][driver]['profiles'][profile_name] # If cloning on Linode, size and image are not necessary. # They are obtained from the to-be-cloned VM. if driver == 'linode' and profile_key.get('clonefrom', False): non_image_drivers.append('linode') non_size_drivers.append('linode') elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')): non_image_drivers.append('gce') # If cloning on VMware, specifying image is not necessary. if driver == 'vmware' and 'image' not in list(profile_key.keys()): non_image_drivers.append('vmware') if driver not in non_image_drivers: required_keys.append('image') if driver == 'vmware': required_keys.append('datastore') elif driver in ['linode', 'virtualbox']: required_keys.append('clonefrom') elif driver == 'nova': nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume'] if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]): required_keys.extend(nova_image_keys) if driver not in non_size_drivers: required_keys.append('size') # Check if required fields are supplied in the provider config. If they # are present, remove it from the required_keys list. for item in list(required_keys): if item in provider_key: required_keys.remove(item) # If a vm_ dict was passed in, use that information to get any other configs # that we might have missed thus far, such as a option provided in a map file. if vm_: for item in list(required_keys): if item in vm_: required_keys.remove(item) # Check for remaining required parameters in the profile config. for item in required_keys: if profile_key.get(item, None) is None: # There's at least one required configuration item which is not set. log.error( "The required '%s' configuration setting is missing from " "the '%s' profile, which is configured under the '%s' alias.", item, profile_name, alias ) return False return True
[ "def", "is_profile_configured", "(", "opts", ",", "provider", ",", "profile_name", ",", "vm_", "=", "None", ")", ":", "# Standard dict keys required by all drivers.", "required_keys", "=", "[", "'provider'", "]", "alias", ",", "driver", "=", "provider", ".", "spli...
Check if the requested profile contains the minimum required parameters for a profile. Required parameters include image and provider for all drivers, while some drivers also require size keys. .. versionadded:: 2015.8.0
[ "Check", "if", "the", "requested", "profile", "contains", "the", "minimum", "required", "parameters", "for", "a", "profile", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3424-L3499
train
saltstack/salt
salt/config/__init__.py
check_driver_dependencies
def check_driver_dependencies(driver, dependencies): ''' Check if the driver's dependencies are available. .. versionadded:: 2015.8.0 driver The name of the driver. dependencies The dictionary of dependencies to check. ''' ret = True for key, value in six.iteritems(dependencies): if value is False: log.warning( "Missing dependency: '%s'. The %s driver requires " "'%s' to be installed.", key, driver, key ) ret = False return ret
python
def check_driver_dependencies(driver, dependencies): ''' Check if the driver's dependencies are available. .. versionadded:: 2015.8.0 driver The name of the driver. dependencies The dictionary of dependencies to check. ''' ret = True for key, value in six.iteritems(dependencies): if value is False: log.warning( "Missing dependency: '%s'. The %s driver requires " "'%s' to be installed.", key, driver, key ) ret = False return ret
[ "def", "check_driver_dependencies", "(", "driver", ",", "dependencies", ")", ":", "ret", "=", "True", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "dependencies", ")", ":", "if", "value", "is", "False", ":", "log", ".", "warning", "(",...
Check if the driver's dependencies are available. .. versionadded:: 2015.8.0 driver The name of the driver. dependencies The dictionary of dependencies to check.
[ "Check", "if", "the", "driver", "s", "dependencies", "are", "available", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3502-L3523
train
saltstack/salt
salt/config/__init__.py
_cache_id
def _cache_id(minion_id, cache_file): ''' Helper function, writes minion id to a cache file. ''' path = os.path.dirname(cache_file) try: if not os.path.isdir(path): os.makedirs(path) except OSError as exc: # Handle race condition where dir is created after os.path.isdir check if os.path.isdir(path): pass else: log.error('Failed to create dirs to minion_id file: %s', exc) try: with salt.utils.files.fopen(cache_file, 'w') as idf: idf.write(minion_id) except (IOError, OSError) as exc: log.error('Could not cache minion ID: %s', exc)
python
def _cache_id(minion_id, cache_file): ''' Helper function, writes minion id to a cache file. ''' path = os.path.dirname(cache_file) try: if not os.path.isdir(path): os.makedirs(path) except OSError as exc: # Handle race condition where dir is created after os.path.isdir check if os.path.isdir(path): pass else: log.error('Failed to create dirs to minion_id file: %s', exc) try: with salt.utils.files.fopen(cache_file, 'w') as idf: idf.write(minion_id) except (IOError, OSError) as exc: log.error('Could not cache minion ID: %s', exc)
[ "def", "_cache_id", "(", "minion_id", ",", "cache_file", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "cache_file", ")", "try", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "os", ".", "makedirs", "(", ...
Helper function, writes minion id to a cache file.
[ "Helper", "function", "writes", "minion", "id", "to", "a", "cache", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3528-L3547
train
saltstack/salt
salt/config/__init__.py
call_id_function
def call_id_function(opts): ''' Evaluate the function that determines the ID if the 'id_function' option is set and return the result ''' if opts.get('id'): return opts['id'] # Import 'salt.loader' here to avoid a circular dependency import salt.loader as loader if isinstance(opts['id_function'], six.string_types): mod_fun = opts['id_function'] fun_kwargs = {} elif isinstance(opts['id_function'], dict): mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function'])) if fun_kwargs is None: fun_kwargs = {} else: log.error('\'id_function\' option is neither a string nor a dictionary') sys.exit(salt.defaults.exitcodes.EX_GENERIC) # split module and function and try loading the module mod, fun = mod_fun.split('.') if not opts.get('grains'): # Get grains for use by the module opts['grains'] = loader.grains(opts) try: id_mod = loader.raw_mod(opts, mod, fun) if not id_mod: raise KeyError # we take whatever the module returns as the minion ID newid = id_mod[mod_fun](**fun_kwargs) if not isinstance(newid, six.string_types) or not newid: log.error( 'Function %s returned value "%s" of type %s instead of string', mod_fun, newid, type(newid) ) sys.exit(salt.defaults.exitcodes.EX_GENERIC) log.info('Evaluated minion ID from module: %s', mod_fun) return newid except TypeError: log.error( 'Function arguments %s are incorrect for function %s', fun_kwargs, mod_fun ) sys.exit(salt.defaults.exitcodes.EX_GENERIC) except KeyError: log.error('Failed to load module %s', mod_fun) sys.exit(salt.defaults.exitcodes.EX_GENERIC)
python
def call_id_function(opts): ''' Evaluate the function that determines the ID if the 'id_function' option is set and return the result ''' if opts.get('id'): return opts['id'] # Import 'salt.loader' here to avoid a circular dependency import salt.loader as loader if isinstance(opts['id_function'], six.string_types): mod_fun = opts['id_function'] fun_kwargs = {} elif isinstance(opts['id_function'], dict): mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function'])) if fun_kwargs is None: fun_kwargs = {} else: log.error('\'id_function\' option is neither a string nor a dictionary') sys.exit(salt.defaults.exitcodes.EX_GENERIC) # split module and function and try loading the module mod, fun = mod_fun.split('.') if not opts.get('grains'): # Get grains for use by the module opts['grains'] = loader.grains(opts) try: id_mod = loader.raw_mod(opts, mod, fun) if not id_mod: raise KeyError # we take whatever the module returns as the minion ID newid = id_mod[mod_fun](**fun_kwargs) if not isinstance(newid, six.string_types) or not newid: log.error( 'Function %s returned value "%s" of type %s instead of string', mod_fun, newid, type(newid) ) sys.exit(salt.defaults.exitcodes.EX_GENERIC) log.info('Evaluated minion ID from module: %s', mod_fun) return newid except TypeError: log.error( 'Function arguments %s are incorrect for function %s', fun_kwargs, mod_fun ) sys.exit(salt.defaults.exitcodes.EX_GENERIC) except KeyError: log.error('Failed to load module %s', mod_fun) sys.exit(salt.defaults.exitcodes.EX_GENERIC)
[ "def", "call_id_function", "(", "opts", ")", ":", "if", "opts", ".", "get", "(", "'id'", ")", ":", "return", "opts", "[", "'id'", "]", "# Import 'salt.loader' here to avoid a circular dependency", "import", "salt", ".", "loader", "as", "loader", "if", "isinstanc...
Evaluate the function that determines the ID if the 'id_function' option is set and return the result
[ "Evaluate", "the", "function", "that", "determines", "the", "ID", "if", "the", "id_function", "option", "is", "set", "and", "return", "the", "result" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3550-L3600
train
saltstack/salt
salt/config/__init__.py
remove_domain_from_fqdn
def remove_domain_from_fqdn(opts, newid): ''' Depending on the values of `minion_id_remove_domain`, remove all domains or a single domain from a FQDN, effectivly generating a hostname. ''' opt_domain = opts.get('minion_id_remove_domain') if opt_domain is True: if '.' in newid: # Remove any domain newid, xdomain = newid.split('.', 1) log.debug('Removed any domain (%s) from minion id.', xdomain) else: # Must be string type if newid.upper().endswith('.' + opt_domain.upper()): # Remove single domain newid = newid[:-len('.' + opt_domain)] log.debug('Removed single domain %s from minion id.', opt_domain) return newid
python
def remove_domain_from_fqdn(opts, newid): ''' Depending on the values of `minion_id_remove_domain`, remove all domains or a single domain from a FQDN, effectivly generating a hostname. ''' opt_domain = opts.get('minion_id_remove_domain') if opt_domain is True: if '.' in newid: # Remove any domain newid, xdomain = newid.split('.', 1) log.debug('Removed any domain (%s) from minion id.', xdomain) else: # Must be string type if newid.upper().endswith('.' + opt_domain.upper()): # Remove single domain newid = newid[:-len('.' + opt_domain)] log.debug('Removed single domain %s from minion id.', opt_domain) return newid
[ "def", "remove_domain_from_fqdn", "(", "opts", ",", "newid", ")", ":", "opt_domain", "=", "opts", ".", "get", "(", "'minion_id_remove_domain'", ")", "if", "opt_domain", "is", "True", ":", "if", "'.'", "in", "newid", ":", "# Remove any domain", "newid", ",", ...
Depending on the values of `minion_id_remove_domain`, remove all domains or a single domain from a FQDN, effectivly generating a hostname.
[ "Depending", "on", "the", "values", "of", "minion_id_remove_domain", "remove", "all", "domains", "or", "a", "single", "domain", "from", "a", "FQDN", "effectivly", "generating", "a", "hostname", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3603-L3620
train
saltstack/salt
salt/config/__init__.py
get_id
def get_id(opts, cache_minion_id=False): ''' Guess the id of the minion. If CONFIG_DIR/minion_id exists, use the cached minion ID from that file. If no minion id is configured, use multiple sources to find a FQDN. If no FQDN is found you may get an ip address. Returns two values: the detected ID, and a boolean value noting whether or not an IP address is being used for the ID. ''' if opts['root_dir'] is None: root_dir = salt.syspaths.ROOT_DIR else: root_dir = opts['root_dir'] config_dir = salt.syspaths.CONFIG_DIR if config_dir.startswith(salt.syspaths.ROOT_DIR): config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1] # Check for cached minion ID id_cache = os.path.join(root_dir, config_dir.lstrip(os.path.sep), 'minion_id') if opts.get('minion_id_caching', True): try: with salt.utils.files.fopen(id_cache) as idf: name = salt.utils.stringutils.to_unicode(idf.readline().strip()) bname = salt.utils.stringutils.to_bytes(name) if bname.startswith(codecs.BOM): # Remove BOM if exists name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1)) if name and name != 'localhost': log.debug('Using cached minion ID from %s: %s', id_cache, name) return name, False except (IOError, OSError): pass if '__role' in opts and opts.get('__role') == 'minion': log.debug( 'Guessing ID. The id can be explicitly set in %s', os.path.join(salt.syspaths.CONFIG_DIR, 'minion') ) if opts.get('id_function'): newid = call_id_function(opts) else: newid = salt.utils.network.generate_minion_id() if opts.get('minion_id_lowercase'): newid = newid.lower() log.debug('Changed minion id %s to lowercase.', newid) # Optionally remove one or many domains in a generated minion id if opts.get('minion_id_remove_domain'): newid = remove_domain_from_fqdn(opts, newid) if '__role' in opts and opts.get('__role') == 'minion': if opts.get('id_function'): log.debug( 'Found minion id from external function %s: %s', opts['id_function'], newid ) else: log.debug('Found minion id from generate_minion_id(): %s', newid) if cache_minion_id and opts.get('minion_id_caching', True): _cache_id(newid, id_cache) is_ipv4 = salt.utils.network.is_ipv4(newid) return newid, is_ipv4
python
def get_id(opts, cache_minion_id=False): ''' Guess the id of the minion. If CONFIG_DIR/minion_id exists, use the cached minion ID from that file. If no minion id is configured, use multiple sources to find a FQDN. If no FQDN is found you may get an ip address. Returns two values: the detected ID, and a boolean value noting whether or not an IP address is being used for the ID. ''' if opts['root_dir'] is None: root_dir = salt.syspaths.ROOT_DIR else: root_dir = opts['root_dir'] config_dir = salt.syspaths.CONFIG_DIR if config_dir.startswith(salt.syspaths.ROOT_DIR): config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1] # Check for cached minion ID id_cache = os.path.join(root_dir, config_dir.lstrip(os.path.sep), 'minion_id') if opts.get('minion_id_caching', True): try: with salt.utils.files.fopen(id_cache) as idf: name = salt.utils.stringutils.to_unicode(idf.readline().strip()) bname = salt.utils.stringutils.to_bytes(name) if bname.startswith(codecs.BOM): # Remove BOM if exists name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1)) if name and name != 'localhost': log.debug('Using cached minion ID from %s: %s', id_cache, name) return name, False except (IOError, OSError): pass if '__role' in opts and opts.get('__role') == 'minion': log.debug( 'Guessing ID. The id can be explicitly set in %s', os.path.join(salt.syspaths.CONFIG_DIR, 'minion') ) if opts.get('id_function'): newid = call_id_function(opts) else: newid = salt.utils.network.generate_minion_id() if opts.get('minion_id_lowercase'): newid = newid.lower() log.debug('Changed minion id %s to lowercase.', newid) # Optionally remove one or many domains in a generated minion id if opts.get('minion_id_remove_domain'): newid = remove_domain_from_fqdn(opts, newid) if '__role' in opts and opts.get('__role') == 'minion': if opts.get('id_function'): log.debug( 'Found minion id from external function %s: %s', opts['id_function'], newid ) else: log.debug('Found minion id from generate_minion_id(): %s', newid) if cache_minion_id and opts.get('minion_id_caching', True): _cache_id(newid, id_cache) is_ipv4 = salt.utils.network.is_ipv4(newid) return newid, is_ipv4
[ "def", "get_id", "(", "opts", ",", "cache_minion_id", "=", "False", ")", ":", "if", "opts", "[", "'root_dir'", "]", "is", "None", ":", "root_dir", "=", "salt", ".", "syspaths", ".", "ROOT_DIR", "else", ":", "root_dir", "=", "opts", "[", "'root_dir'", "...
Guess the id of the minion. If CONFIG_DIR/minion_id exists, use the cached minion ID from that file. If no minion id is configured, use multiple sources to find a FQDN. If no FQDN is found you may get an ip address. Returns two values: the detected ID, and a boolean value noting whether or not an IP address is being used for the ID.
[ "Guess", "the", "id", "of", "the", "minion", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3623-L3690
train
saltstack/salt
salt/config/__init__.py
_update_ssl_config
def _update_ssl_config(opts): ''' Resolves string names to integer constant in ssl configuration. ''' if opts['ssl'] in (None, False): opts['ssl'] = None return if opts['ssl'] is True: opts['ssl'] = {} return import ssl for key, prefix in (('cert_reqs', 'CERT_'), ('ssl_version', 'PROTOCOL_')): val = opts['ssl'].get(key) if val is None: continue if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val): message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \ .format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)])) log.error(message) raise salt.exceptions.SaltConfigurationError(message) opts['ssl'][key] = getattr(ssl, val)
python
def _update_ssl_config(opts): ''' Resolves string names to integer constant in ssl configuration. ''' if opts['ssl'] in (None, False): opts['ssl'] = None return if opts['ssl'] is True: opts['ssl'] = {} return import ssl for key, prefix in (('cert_reqs', 'CERT_'), ('ssl_version', 'PROTOCOL_')): val = opts['ssl'].get(key) if val is None: continue if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val): message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \ .format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)])) log.error(message) raise salt.exceptions.SaltConfigurationError(message) opts['ssl'][key] = getattr(ssl, val)
[ "def", "_update_ssl_config", "(", "opts", ")", ":", "if", "opts", "[", "'ssl'", "]", "in", "(", "None", ",", "False", ")", ":", "opts", "[", "'ssl'", "]", "=", "None", "return", "if", "opts", "[", "'ssl'", "]", "is", "True", ":", "opts", "[", "'s...
Resolves string names to integer constant in ssl configuration.
[ "Resolves", "string", "names", "to", "integer", "constant", "in", "ssl", "configuration", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3693-L3714
train
saltstack/salt
salt/config/__init__.py
_adjust_log_file_override
def _adjust_log_file_override(overrides, default_log_file): ''' Adjusts the log_file based on the log_dir override ''' if overrides.get('log_dir'): # Adjust log_file if a log_dir override is introduced if overrides.get('log_file'): if not os.path.isabs(overrides['log_file']): # Prepend log_dir if log_file is relative overrides['log_file'] = os.path.join(overrides['log_dir'], overrides['log_file']) else: # Create the log_file override overrides['log_file'] = \ os.path.join(overrides['log_dir'], os.path.basename(default_log_file))
python
def _adjust_log_file_override(overrides, default_log_file): ''' Adjusts the log_file based on the log_dir override ''' if overrides.get('log_dir'): # Adjust log_file if a log_dir override is introduced if overrides.get('log_file'): if not os.path.isabs(overrides['log_file']): # Prepend log_dir if log_file is relative overrides['log_file'] = os.path.join(overrides['log_dir'], overrides['log_file']) else: # Create the log_file override overrides['log_file'] = \ os.path.join(overrides['log_dir'], os.path.basename(default_log_file))
[ "def", "_adjust_log_file_override", "(", "overrides", ",", "default_log_file", ")", ":", "if", "overrides", ".", "get", "(", "'log_dir'", ")", ":", "# Adjust log_file if a log_dir override is introduced", "if", "overrides", ".", "get", "(", "'log_file'", ")", ":", "...
Adjusts the log_file based on the log_dir override
[ "Adjusts", "the", "log_file", "based", "on", "the", "log_dir", "override" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3717-L3732
train
saltstack/salt
salt/config/__init__.py
apply_minion_config
def apply_minion_config(overrides=None, defaults=None, cache_minion_id=False, minion_id=None): ''' Returns minion configurations dict. ''' if defaults is None: defaults = DEFAULT_MINION_OPTS.copy() if overrides is None: overrides = {} opts = defaults.copy() opts['__role'] = 'minion' _adjust_log_file_override(overrides, defaults['log_file']) if overrides: opts.update(overrides) if 'environment' in opts: if opts['saltenv'] is not None: log.warning( 'The \'saltenv\' and \'environment\' minion config options ' 'cannot both be used. Ignoring \'environment\' in favor of ' '\'saltenv\'.', ) # Set environment to saltenv in case someone's custom module is # refrencing __opts__['environment'] opts['environment'] = opts['saltenv'] else: log.warning( 'The \'environment\' minion config option has been renamed ' 'to \'saltenv\'. Using %s as the \'saltenv\' config value.', opts['environment'] ) opts['saltenv'] = opts['environment'] for idx, val in enumerate(opts['fileserver_backend']): if val in ('git', 'hg', 'svn', 'minion'): new_val = val + 'fs' log.debug( 'Changed %s to %s in minion opts\' fileserver_backend list', val, new_val ) opts['fileserver_backend'][idx] = new_val opts['__cli'] = salt.utils.stringutils.to_unicode( os.path.basename(sys.argv[0]) ) # No ID provided. Will getfqdn save us? using_ip_for_id = False if not opts.get('id'): if minion_id: opts['id'] = minion_id else: opts['id'], using_ip_for_id = get_id( opts, cache_minion_id=cache_minion_id) # it does not make sense to append a domain to an IP based id if not using_ip_for_id and 'append_domain' in opts: opts['id'] = _append_domain(opts) for directory in opts.get('append_minionid_config_dirs', []): if directory in ('pki_dir', 'cachedir', 'extension_modules'): newdirectory = os.path.join(opts[directory], opts['id']) opts[directory] = newdirectory elif directory == 'default_include' and directory in opts: include_dir = os.path.dirname(opts[directory]) new_include_dir = os.path.join(include_dir, opts['id'], os.path.basename(opts[directory])) opts[directory] = new_include_dir # pidfile can be in the list of append_minionid_config_dirs, but pidfile # is the actual path with the filename, not a directory. if 'pidfile' in opts.get('append_minionid_config_dirs', []): newpath_list = os.path.split(opts['pidfile']) opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1]) if len(opts['sock_dir']) > len(opts['cachedir']) + 10: opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix') # Enabling open mode requires that the value be set to True, and # nothing else! opts['open_mode'] = opts['open_mode'] is True opts['file_roots'] = _validate_file_roots(opts['file_roots']) opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots']) # Make sure ext_mods gets set if it is an untrue value # (here to catch older bad configs) opts['extension_modules'] = ( opts.get('extension_modules') or os.path.join(opts['cachedir'], 'extmods') ) # Set up the utils_dirs location from the extension_modules location opts['utils_dirs'] = ( opts.get('utils_dirs') or [os.path.join(opts['extension_modules'], 'utils')] ) # Insert all 'utils_dirs' directories to the system path insert_system_path(opts, opts['utils_dirs']) # Prepend root_dir to other paths prepend_root_dirs = [ 'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile', ] # These can be set to syslog, so, not actual paths on the system for config_key in ('log_file', 'key_logfile'): if urlparse(opts.get(config_key, '')).scheme == '': prepend_root_dirs.append(config_key) prepend_root_dir(opts, prepend_root_dirs) # if there is no beacons option yet, add an empty beacons dict if 'beacons' not in opts: opts['beacons'] = {} if overrides.get('ipc_write_buffer', '') == 'dynamic': opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER # Make sure hash_type is lowercase opts['hash_type'] = opts['hash_type'].lower() # Check and update TLS/SSL configuration _update_ssl_config(opts) _update_discovery_config(opts) return opts
python
def apply_minion_config(overrides=None, defaults=None, cache_minion_id=False, minion_id=None): ''' Returns minion configurations dict. ''' if defaults is None: defaults = DEFAULT_MINION_OPTS.copy() if overrides is None: overrides = {} opts = defaults.copy() opts['__role'] = 'minion' _adjust_log_file_override(overrides, defaults['log_file']) if overrides: opts.update(overrides) if 'environment' in opts: if opts['saltenv'] is not None: log.warning( 'The \'saltenv\' and \'environment\' minion config options ' 'cannot both be used. Ignoring \'environment\' in favor of ' '\'saltenv\'.', ) # Set environment to saltenv in case someone's custom module is # refrencing __opts__['environment'] opts['environment'] = opts['saltenv'] else: log.warning( 'The \'environment\' minion config option has been renamed ' 'to \'saltenv\'. Using %s as the \'saltenv\' config value.', opts['environment'] ) opts['saltenv'] = opts['environment'] for idx, val in enumerate(opts['fileserver_backend']): if val in ('git', 'hg', 'svn', 'minion'): new_val = val + 'fs' log.debug( 'Changed %s to %s in minion opts\' fileserver_backend list', val, new_val ) opts['fileserver_backend'][idx] = new_val opts['__cli'] = salt.utils.stringutils.to_unicode( os.path.basename(sys.argv[0]) ) # No ID provided. Will getfqdn save us? using_ip_for_id = False if not opts.get('id'): if minion_id: opts['id'] = minion_id else: opts['id'], using_ip_for_id = get_id( opts, cache_minion_id=cache_minion_id) # it does not make sense to append a domain to an IP based id if not using_ip_for_id and 'append_domain' in opts: opts['id'] = _append_domain(opts) for directory in opts.get('append_minionid_config_dirs', []): if directory in ('pki_dir', 'cachedir', 'extension_modules'): newdirectory = os.path.join(opts[directory], opts['id']) opts[directory] = newdirectory elif directory == 'default_include' and directory in opts: include_dir = os.path.dirname(opts[directory]) new_include_dir = os.path.join(include_dir, opts['id'], os.path.basename(opts[directory])) opts[directory] = new_include_dir # pidfile can be in the list of append_minionid_config_dirs, but pidfile # is the actual path with the filename, not a directory. if 'pidfile' in opts.get('append_minionid_config_dirs', []): newpath_list = os.path.split(opts['pidfile']) opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1]) if len(opts['sock_dir']) > len(opts['cachedir']) + 10: opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix') # Enabling open mode requires that the value be set to True, and # nothing else! opts['open_mode'] = opts['open_mode'] is True opts['file_roots'] = _validate_file_roots(opts['file_roots']) opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots']) # Make sure ext_mods gets set if it is an untrue value # (here to catch older bad configs) opts['extension_modules'] = ( opts.get('extension_modules') or os.path.join(opts['cachedir'], 'extmods') ) # Set up the utils_dirs location from the extension_modules location opts['utils_dirs'] = ( opts.get('utils_dirs') or [os.path.join(opts['extension_modules'], 'utils')] ) # Insert all 'utils_dirs' directories to the system path insert_system_path(opts, opts['utils_dirs']) # Prepend root_dir to other paths prepend_root_dirs = [ 'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile', ] # These can be set to syslog, so, not actual paths on the system for config_key in ('log_file', 'key_logfile'): if urlparse(opts.get(config_key, '')).scheme == '': prepend_root_dirs.append(config_key) prepend_root_dir(opts, prepend_root_dirs) # if there is no beacons option yet, add an empty beacons dict if 'beacons' not in opts: opts['beacons'] = {} if overrides.get('ipc_write_buffer', '') == 'dynamic': opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER # Make sure hash_type is lowercase opts['hash_type'] = opts['hash_type'].lower() # Check and update TLS/SSL configuration _update_ssl_config(opts) _update_discovery_config(opts) return opts
[ "def", "apply_minion_config", "(", "overrides", "=", "None", ",", "defaults", "=", "None", ",", "cache_minion_id", "=", "False", ",", "minion_id", "=", "None", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "DEFAULT_MINION_OPTS", ".", "copy"...
Returns minion configurations dict.
[ "Returns", "minion", "configurations", "dict", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3735-L3864
train
saltstack/salt
salt/config/__init__.py
_update_discovery_config
def _update_discovery_config(opts): ''' Update discovery config for all instances. :param opts: :return: ''' if opts.get('discovery') not in (None, False): if opts['discovery'] is True: opts['discovery'] = {} discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False} for key in opts['discovery']: if key not in discovery_config: raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key)) if opts.get('__role') != 'minion': for key in ['attempts', 'pause', 'match']: del discovery_config[key] opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
python
def _update_discovery_config(opts): ''' Update discovery config for all instances. :param opts: :return: ''' if opts.get('discovery') not in (None, False): if opts['discovery'] is True: opts['discovery'] = {} discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False} for key in opts['discovery']: if key not in discovery_config: raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key)) if opts.get('__role') != 'minion': for key in ['attempts', 'pause', 'match']: del discovery_config[key] opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
[ "def", "_update_discovery_config", "(", "opts", ")", ":", "if", "opts", ".", "get", "(", "'discovery'", ")", "not", "in", "(", "None", ",", "False", ")", ":", "if", "opts", "[", "'discovery'", "]", "is", "True", ":", "opts", "[", "'discovery'", "]", ...
Update discovery config for all instances. :param opts: :return:
[ "Update", "discovery", "config", "for", "all", "instances", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3867-L3884
train
saltstack/salt
salt/config/__init__.py
master_config
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False): ''' Reads in the master configuration file and sets up default options This is useful for running the actual master daemon. For running Master-side client interfaces that need the master opts see :py:func:`salt.client.client_config`. ''' if defaults is None: defaults = DEFAULT_MASTER_OPTS.copy() if not os.environ.get(env_var, None): # No valid setting was given using the configuration variable. # Lets see is SALT_CONFIG_DIR is of any use salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None) if salt_config_dir: env_config_file_path = os.path.join(salt_config_dir, 'master') if salt_config_dir and os.path.isfile(env_config_file_path): # We can get a configuration file using SALT_CONFIG_DIR, let's # update the environment with this information os.environ[env_var] = env_config_file_path overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file']) default_include = overrides.get('default_include', defaults['default_include']) include = overrides.get('include', []) overrides.update(include_config(default_include, path, verbose=False, exit_on_config_errors=exit_on_config_errors)) overrides.update(include_config(include, path, verbose=True, exit_on_config_errors=exit_on_config_errors)) opts = apply_master_config(overrides, defaults) _validate_ssh_minion_opts(opts) _validate_opts(opts) # If 'nodegroups:' is uncommented in the master config file, and there are # no nodegroups defined, opts['nodegroups'] will be None. Fix this by # reverting this value to the default, as if 'nodegroups:' was commented # out or not present. if opts.get('nodegroups') is None: opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {}) if salt.utils.data.is_dictlist(opts['nodegroups']): opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups']) apply_sdb(opts) return opts
python
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False): ''' Reads in the master configuration file and sets up default options This is useful for running the actual master daemon. For running Master-side client interfaces that need the master opts see :py:func:`salt.client.client_config`. ''' if defaults is None: defaults = DEFAULT_MASTER_OPTS.copy() if not os.environ.get(env_var, None): # No valid setting was given using the configuration variable. # Lets see is SALT_CONFIG_DIR is of any use salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None) if salt_config_dir: env_config_file_path = os.path.join(salt_config_dir, 'master') if salt_config_dir and os.path.isfile(env_config_file_path): # We can get a configuration file using SALT_CONFIG_DIR, let's # update the environment with this information os.environ[env_var] = env_config_file_path overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file']) default_include = overrides.get('default_include', defaults['default_include']) include = overrides.get('include', []) overrides.update(include_config(default_include, path, verbose=False, exit_on_config_errors=exit_on_config_errors)) overrides.update(include_config(include, path, verbose=True, exit_on_config_errors=exit_on_config_errors)) opts = apply_master_config(overrides, defaults) _validate_ssh_minion_opts(opts) _validate_opts(opts) # If 'nodegroups:' is uncommented in the master config file, and there are # no nodegroups defined, opts['nodegroups'] will be None. Fix this by # reverting this value to the default, as if 'nodegroups:' was commented # out or not present. if opts.get('nodegroups') is None: opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {}) if salt.utils.data.is_dictlist(opts['nodegroups']): opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups']) apply_sdb(opts) return opts
[ "def", "master_config", "(", "path", ",", "env_var", "=", "'SALT_MASTER_CONFIG'", ",", "defaults", "=", "None", ",", "exit_on_config_errors", "=", "False", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "DEFAULT_MASTER_OPTS", ".", "copy", "(",...
Reads in the master configuration file and sets up default options This is useful for running the actual master daemon. For running Master-side client interfaces that need the master opts see :py:func:`salt.client.client_config`.
[ "Reads", "in", "the", "master", "configuration", "file", "and", "sets", "up", "default", "options" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3887-L3930
train
saltstack/salt
salt/config/__init__.py
apply_master_config
def apply_master_config(overrides=None, defaults=None): ''' Returns master configurations dict. ''' if defaults is None: defaults = DEFAULT_MASTER_OPTS.copy() if overrides is None: overrides = {} opts = defaults.copy() opts['__role'] = 'master' _adjust_log_file_override(overrides, defaults['log_file']) if overrides: opts.update(overrides) opts['__cli'] = salt.utils.stringutils.to_unicode( os.path.basename(sys.argv[0]) ) if 'environment' in opts: if opts['saltenv'] is not None: log.warning( 'The \'saltenv\' and \'environment\' master config options ' 'cannot both be used. Ignoring \'environment\' in favor of ' '\'saltenv\'.', ) # Set environment to saltenv in case someone's custom runner is # refrencing __opts__['environment'] opts['environment'] = opts['saltenv'] else: log.warning( 'The \'environment\' master config option has been renamed ' 'to \'saltenv\'. Using %s as the \'saltenv\' config value.', opts['environment'] ) opts['saltenv'] = opts['environment'] if six.PY2 and 'rest_cherrypy' in opts: # CherryPy is not unicode-compatible opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy']) for idx, val in enumerate(opts['fileserver_backend']): if val in ('git', 'hg', 'svn', 'minion'): new_val = val + 'fs' log.debug( 'Changed %s to %s in master opts\' fileserver_backend list', val, new_val ) opts['fileserver_backend'][idx] = new_val if len(opts['sock_dir']) > len(opts['cachedir']) + 10: opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix') opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens') opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics') # Make sure ext_mods gets set if it is an untrue value # (here to catch older bad configs) opts['extension_modules'] = ( opts.get('extension_modules') or os.path.join(opts['cachedir'], 'extmods') ) # Set up the utils_dirs location from the extension_modules location opts['utils_dirs'] = ( opts.get('utils_dirs') or [os.path.join(opts['extension_modules'], 'utils')] ) # Insert all 'utils_dirs' directories to the system path insert_system_path(opts, opts['utils_dirs']) if overrides.get('ipc_write_buffer', '') == 'dynamic': opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER using_ip_for_id = False append_master = False if not opts.get('id'): opts['id'], using_ip_for_id = get_id( opts, cache_minion_id=None) append_master = True # it does not make sense to append a domain to an IP based id if not using_ip_for_id and 'append_domain' in opts: opts['id'] = _append_domain(opts) if append_master: opts['id'] += '_master' # Prepend root_dir to other paths prepend_root_dirs = [ 'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules', 'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir', 'sqlite_queue_dir', 'autosign_grains_dir' ] # These can be set to syslog, so, not actual paths on the system for config_key in ('log_file', 'key_logfile', 'ssh_log_file'): log_setting = opts.get(config_key, '') if log_setting is None: continue if urlparse(log_setting).scheme == '': prepend_root_dirs.append(config_key) prepend_root_dir(opts, prepend_root_dirs) # Enabling open mode requires that the value be set to True, and # nothing else! opts['open_mode'] = opts['open_mode'] is True opts['auto_accept'] = opts['auto_accept'] is True opts['file_roots'] = _validate_file_roots(opts['file_roots']) opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots']) if opts['file_ignore_regex']: # If file_ignore_regex was given, make sure it's wrapped in a list. # Only keep valid regex entries for improved performance later on. if isinstance(opts['file_ignore_regex'], six.string_types): ignore_regex = [opts['file_ignore_regex']] elif isinstance(opts['file_ignore_regex'], list): ignore_regex = opts['file_ignore_regex'] opts['file_ignore_regex'] = [] for regex in ignore_regex: try: # Can't store compiled regex itself in opts (breaks # serialization) re.compile(regex) opts['file_ignore_regex'].append(regex) except Exception: log.warning( 'Unable to parse file_ignore_regex. Skipping: %s', regex ) if opts['file_ignore_glob']: # If file_ignore_glob was given, make sure it's wrapped in a list. if isinstance(opts['file_ignore_glob'], six.string_types): opts['file_ignore_glob'] = [opts['file_ignore_glob']] # Let's make sure `worker_threads` does not drop below 3 which has proven # to make `salt.modules.publish` not work under the test-suite. if opts['worker_threads'] < 3 and opts.get('peer', None): log.warning( "The 'worker_threads' setting in '%s' cannot be lower than " '3. Resetting it to the default value of 3.', opts['conf_file'] ) opts['worker_threads'] = 3 opts.setdefault('pillar_source_merging_strategy', 'smart') # Make sure hash_type is lowercase opts['hash_type'] = opts['hash_type'].lower() # Check and update TLS/SSL configuration _update_ssl_config(opts) _update_discovery_config(opts) return opts
python
def apply_master_config(overrides=None, defaults=None): ''' Returns master configurations dict. ''' if defaults is None: defaults = DEFAULT_MASTER_OPTS.copy() if overrides is None: overrides = {} opts = defaults.copy() opts['__role'] = 'master' _adjust_log_file_override(overrides, defaults['log_file']) if overrides: opts.update(overrides) opts['__cli'] = salt.utils.stringutils.to_unicode( os.path.basename(sys.argv[0]) ) if 'environment' in opts: if opts['saltenv'] is not None: log.warning( 'The \'saltenv\' and \'environment\' master config options ' 'cannot both be used. Ignoring \'environment\' in favor of ' '\'saltenv\'.', ) # Set environment to saltenv in case someone's custom runner is # refrencing __opts__['environment'] opts['environment'] = opts['saltenv'] else: log.warning( 'The \'environment\' master config option has been renamed ' 'to \'saltenv\'. Using %s as the \'saltenv\' config value.', opts['environment'] ) opts['saltenv'] = opts['environment'] if six.PY2 and 'rest_cherrypy' in opts: # CherryPy is not unicode-compatible opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy']) for idx, val in enumerate(opts['fileserver_backend']): if val in ('git', 'hg', 'svn', 'minion'): new_val = val + 'fs' log.debug( 'Changed %s to %s in master opts\' fileserver_backend list', val, new_val ) opts['fileserver_backend'][idx] = new_val if len(opts['sock_dir']) > len(opts['cachedir']) + 10: opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix') opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens') opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics') # Make sure ext_mods gets set if it is an untrue value # (here to catch older bad configs) opts['extension_modules'] = ( opts.get('extension_modules') or os.path.join(opts['cachedir'], 'extmods') ) # Set up the utils_dirs location from the extension_modules location opts['utils_dirs'] = ( opts.get('utils_dirs') or [os.path.join(opts['extension_modules'], 'utils')] ) # Insert all 'utils_dirs' directories to the system path insert_system_path(opts, opts['utils_dirs']) if overrides.get('ipc_write_buffer', '') == 'dynamic': opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER using_ip_for_id = False append_master = False if not opts.get('id'): opts['id'], using_ip_for_id = get_id( opts, cache_minion_id=None) append_master = True # it does not make sense to append a domain to an IP based id if not using_ip_for_id and 'append_domain' in opts: opts['id'] = _append_domain(opts) if append_master: opts['id'] += '_master' # Prepend root_dir to other paths prepend_root_dirs = [ 'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules', 'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir', 'sqlite_queue_dir', 'autosign_grains_dir' ] # These can be set to syslog, so, not actual paths on the system for config_key in ('log_file', 'key_logfile', 'ssh_log_file'): log_setting = opts.get(config_key, '') if log_setting is None: continue if urlparse(log_setting).scheme == '': prepend_root_dirs.append(config_key) prepend_root_dir(opts, prepend_root_dirs) # Enabling open mode requires that the value be set to True, and # nothing else! opts['open_mode'] = opts['open_mode'] is True opts['auto_accept'] = opts['auto_accept'] is True opts['file_roots'] = _validate_file_roots(opts['file_roots']) opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots']) if opts['file_ignore_regex']: # If file_ignore_regex was given, make sure it's wrapped in a list. # Only keep valid regex entries for improved performance later on. if isinstance(opts['file_ignore_regex'], six.string_types): ignore_regex = [opts['file_ignore_regex']] elif isinstance(opts['file_ignore_regex'], list): ignore_regex = opts['file_ignore_regex'] opts['file_ignore_regex'] = [] for regex in ignore_regex: try: # Can't store compiled regex itself in opts (breaks # serialization) re.compile(regex) opts['file_ignore_regex'].append(regex) except Exception: log.warning( 'Unable to parse file_ignore_regex. Skipping: %s', regex ) if opts['file_ignore_glob']: # If file_ignore_glob was given, make sure it's wrapped in a list. if isinstance(opts['file_ignore_glob'], six.string_types): opts['file_ignore_glob'] = [opts['file_ignore_glob']] # Let's make sure `worker_threads` does not drop below 3 which has proven # to make `salt.modules.publish` not work under the test-suite. if opts['worker_threads'] < 3 and opts.get('peer', None): log.warning( "The 'worker_threads' setting in '%s' cannot be lower than " '3. Resetting it to the default value of 3.', opts['conf_file'] ) opts['worker_threads'] = 3 opts.setdefault('pillar_source_merging_strategy', 'smart') # Make sure hash_type is lowercase opts['hash_type'] = opts['hash_type'].lower() # Check and update TLS/SSL configuration _update_ssl_config(opts) _update_discovery_config(opts) return opts
[ "def", "apply_master_config", "(", "overrides", "=", "None", ",", "defaults", "=", "None", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "DEFAULT_MASTER_OPTS", ".", "copy", "(", ")", "if", "overrides", "is", "None", ":", "overrides", "=",...
Returns master configurations dict.
[ "Returns", "master", "configurations", "dict", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3933-L4089
train
saltstack/salt
salt/config/__init__.py
client_config
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None): ''' Load Master configuration data Usage: .. code-block:: python import salt.config master_opts = salt.config.client_config('/etc/salt/master') Returns a dictionary of the Salt Master configuration file with necessary options needed to communicate with a locally-running Salt Master daemon. This function searches for client specific configurations and adds them to the data from the master configuration. This is useful for master-side operations like :py:class:`~salt.client.LocalClient`. ''' if defaults is None: defaults = DEFAULT_MASTER_OPTS.copy() xdg_dir = salt.utils.xdg.xdg_config_dir() if os.path.isdir(xdg_dir): client_config_dir = xdg_dir saltrc_config_file = 'saltrc' else: client_config_dir = os.path.expanduser('~') saltrc_config_file = '.saltrc' # Get the token file path from the provided defaults. If not found, specify # our own, sane, default opts = { 'token_file': defaults.get( 'token_file', os.path.join(client_config_dir, 'salt_token') ) } # Update options with the master configuration, either from the provided # path, salt's defaults or provided defaults opts.update( master_config(path, defaults=defaults) ) # Update with the users salt dot file or with the environment variable saltrc_config = os.path.join(client_config_dir, saltrc_config_file) opts.update( load_config( saltrc_config, env_var, saltrc_config ) ) # Make sure we have a proper and absolute path to the token file if 'token_file' in opts: opts['token_file'] = os.path.abspath( os.path.expanduser( opts['token_file'] ) ) # If the token file exists, read and store the contained token if os.path.isfile(opts['token_file']): # Make sure token is still valid expire = opts.get('token_expire', 43200) if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()): with salt.utils.files.fopen(opts['token_file']) as fp_: opts['token'] = fp_.read().strip() # On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost if opts['interface'] == '0.0.0.0': opts['interface'] = '127.0.0.1' # Make sure the master_uri is set if 'master_uri' not in opts: opts['master_uri'] = 'tcp://{ip}:{port}'.format( ip=salt.utils.zeromq.ip_bracket(opts['interface']), port=opts['ret_port'] ) # Return the client options _validate_opts(opts) return opts
python
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None): ''' Load Master configuration data Usage: .. code-block:: python import salt.config master_opts = salt.config.client_config('/etc/salt/master') Returns a dictionary of the Salt Master configuration file with necessary options needed to communicate with a locally-running Salt Master daemon. This function searches for client specific configurations and adds them to the data from the master configuration. This is useful for master-side operations like :py:class:`~salt.client.LocalClient`. ''' if defaults is None: defaults = DEFAULT_MASTER_OPTS.copy() xdg_dir = salt.utils.xdg.xdg_config_dir() if os.path.isdir(xdg_dir): client_config_dir = xdg_dir saltrc_config_file = 'saltrc' else: client_config_dir = os.path.expanduser('~') saltrc_config_file = '.saltrc' # Get the token file path from the provided defaults. If not found, specify # our own, sane, default opts = { 'token_file': defaults.get( 'token_file', os.path.join(client_config_dir, 'salt_token') ) } # Update options with the master configuration, either from the provided # path, salt's defaults or provided defaults opts.update( master_config(path, defaults=defaults) ) # Update with the users salt dot file or with the environment variable saltrc_config = os.path.join(client_config_dir, saltrc_config_file) opts.update( load_config( saltrc_config, env_var, saltrc_config ) ) # Make sure we have a proper and absolute path to the token file if 'token_file' in opts: opts['token_file'] = os.path.abspath( os.path.expanduser( opts['token_file'] ) ) # If the token file exists, read and store the contained token if os.path.isfile(opts['token_file']): # Make sure token is still valid expire = opts.get('token_expire', 43200) if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()): with salt.utils.files.fopen(opts['token_file']) as fp_: opts['token'] = fp_.read().strip() # On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost if opts['interface'] == '0.0.0.0': opts['interface'] = '127.0.0.1' # Make sure the master_uri is set if 'master_uri' not in opts: opts['master_uri'] = 'tcp://{ip}:{port}'.format( ip=salt.utils.zeromq.ip_bracket(opts['interface']), port=opts['ret_port'] ) # Return the client options _validate_opts(opts) return opts
[ "def", "client_config", "(", "path", ",", "env_var", "=", "'SALT_CLIENT_CONFIG'", ",", "defaults", "=", "None", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "DEFAULT_MASTER_OPTS", ".", "copy", "(", ")", "xdg_dir", "=", "salt", ".", "util...
Load Master configuration data Usage: .. code-block:: python import salt.config master_opts = salt.config.client_config('/etc/salt/master') Returns a dictionary of the Salt Master configuration file with necessary options needed to communicate with a locally-running Salt Master daemon. This function searches for client specific configurations and adds them to the data from the master configuration. This is useful for master-side operations like :py:class:`~salt.client.LocalClient`.
[ "Load", "Master", "configuration", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L4092-L4171
train
saltstack/salt
salt/config/__init__.py
api_config
def api_config(path): ''' Read in the Salt Master config file and add additional configs that need to be stubbed out for salt-api ''' # Let's grab a copy of salt-api's required defaults opts = DEFAULT_API_OPTS.copy() # Let's override them with salt's master opts opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy())) # Let's set the pidfile and log_file values in opts to api settings opts.update({ 'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']), 'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']), }) prepend_root_dir(opts, [ 'api_pidfile', 'api_logfile', 'log_file', 'pidfile' ]) return opts
python
def api_config(path): ''' Read in the Salt Master config file and add additional configs that need to be stubbed out for salt-api ''' # Let's grab a copy of salt-api's required defaults opts = DEFAULT_API_OPTS.copy() # Let's override them with salt's master opts opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy())) # Let's set the pidfile and log_file values in opts to api settings opts.update({ 'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']), 'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']), }) prepend_root_dir(opts, [ 'api_pidfile', 'api_logfile', 'log_file', 'pidfile' ]) return opts
[ "def", "api_config", "(", "path", ")", ":", "# Let's grab a copy of salt-api's required defaults", "opts", "=", "DEFAULT_API_OPTS", ".", "copy", "(", ")", "# Let's override them with salt's master opts", "opts", ".", "update", "(", "client_config", "(", "path", ",", "de...
Read in the Salt Master config file and add additional configs that need to be stubbed out for salt-api
[ "Read", "in", "the", "Salt", "Master", "config", "file", "and", "add", "additional", "configs", "that", "need", "to", "be", "stubbed", "out", "for", "salt", "-", "api" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L4174-L4197
train
saltstack/salt
salt/config/__init__.py
spm_config
def spm_config(path): ''' Read in the salt master config file and add additional configs that need to be stubbed out for spm .. versionadded:: 2015.8.0 ''' # Let's grab a copy of salt's master default opts defaults = DEFAULT_MASTER_OPTS.copy() # Let's override them with spm's required defaults defaults.update(DEFAULT_SPM_OPTS) overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file']) default_include = overrides.get('spm_default_include', defaults['spm_default_include']) include = overrides.get('include', []) overrides.update(include_config(default_include, path, verbose=False)) overrides.update(include_config(include, path, verbose=True)) defaults = apply_master_config(overrides, defaults) defaults = apply_spm_config(overrides, defaults) return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
python
def spm_config(path): ''' Read in the salt master config file and add additional configs that need to be stubbed out for spm .. versionadded:: 2015.8.0 ''' # Let's grab a copy of salt's master default opts defaults = DEFAULT_MASTER_OPTS.copy() # Let's override them with spm's required defaults defaults.update(DEFAULT_SPM_OPTS) overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file']) default_include = overrides.get('spm_default_include', defaults['spm_default_include']) include = overrides.get('include', []) overrides.update(include_config(default_include, path, verbose=False)) overrides.update(include_config(include, path, verbose=True)) defaults = apply_master_config(overrides, defaults) defaults = apply_spm_config(overrides, defaults) return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
[ "def", "spm_config", "(", "path", ")", ":", "# Let's grab a copy of salt's master default opts", "defaults", "=", "DEFAULT_MASTER_OPTS", ".", "copy", "(", ")", "# Let's override them with spm's required defaults", "defaults", ".", "update", "(", "DEFAULT_SPM_OPTS", ")", "ov...
Read in the salt master config file and add additional configs that need to be stubbed out for spm .. versionadded:: 2015.8.0
[ "Read", "in", "the", "salt", "master", "config", "file", "and", "add", "additional", "configs", "that", "need", "to", "be", "stubbed", "out", "for", "spm" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L4200-L4221
train
saltstack/salt
salt/config/__init__.py
apply_spm_config
def apply_spm_config(overrides, defaults): ''' Returns the spm configurations dict. .. versionadded:: 2015.8.1 ''' opts = defaults.copy() _adjust_log_file_override(overrides, defaults['log_file']) if overrides: opts.update(overrides) # Prepend root_dir to other paths prepend_root_dirs = [ 'formula_path', 'pillar_path', 'reactor_path', 'spm_cache_dir', 'spm_build_dir' ] # These can be set to syslog, so, not actual paths on the system for config_key in ('spm_logfile',): log_setting = opts.get(config_key, '') if log_setting is None: continue if urlparse(log_setting).scheme == '': prepend_root_dirs.append(config_key) prepend_root_dir(opts, prepend_root_dirs) return opts
python
def apply_spm_config(overrides, defaults): ''' Returns the spm configurations dict. .. versionadded:: 2015.8.1 ''' opts = defaults.copy() _adjust_log_file_override(overrides, defaults['log_file']) if overrides: opts.update(overrides) # Prepend root_dir to other paths prepend_root_dirs = [ 'formula_path', 'pillar_path', 'reactor_path', 'spm_cache_dir', 'spm_build_dir' ] # These can be set to syslog, so, not actual paths on the system for config_key in ('spm_logfile',): log_setting = opts.get(config_key, '') if log_setting is None: continue if urlparse(log_setting).scheme == '': prepend_root_dirs.append(config_key) prepend_root_dir(opts, prepend_root_dirs) return opts
[ "def", "apply_spm_config", "(", "overrides", ",", "defaults", ")", ":", "opts", "=", "defaults", ".", "copy", "(", ")", "_adjust_log_file_override", "(", "overrides", ",", "defaults", "[", "'log_file'", "]", ")", "if", "overrides", ":", "opts", ".", "update"...
Returns the spm configurations dict. .. versionadded:: 2015.8.1
[ "Returns", "the", "spm", "configurations", "dict", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L4224-L4251
train
saltstack/salt
salt/pillar/pillar_ldap.py
_render_template
def _render_template(config_file): ''' Render config template, substituting grains where found. ''' dirname, filename = os.path.split(config_file) env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname)) template = env.get_template(filename) return template.render(__grains__)
python
def _render_template(config_file): ''' Render config template, substituting grains where found. ''' dirname, filename = os.path.split(config_file) env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname)) template = env.get_template(filename) return template.render(__grains__)
[ "def", "_render_template", "(", "config_file", ")", ":", "dirname", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "config_file", ")", "env", "=", "jinja2", ".", "Environment", "(", "loader", "=", "jinja2", ".", "FileSystemLoader", "(", "dirna...
Render config template, substituting grains where found.
[ "Render", "config", "template", "substituting", "grains", "where", "found", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L156-L163
train
saltstack/salt
salt/pillar/pillar_ldap.py
_config
def _config(name, conf, default=None): ''' Return a value for 'name' from the config file options. If the 'name' is not in the config, the 'default' value is returned. This method converts unicode values to str type under python 2. ''' try: value = conf[name] except KeyError: value = default return salt.utils.data.decode(value, to_str=True)
python
def _config(name, conf, default=None): ''' Return a value for 'name' from the config file options. If the 'name' is not in the config, the 'default' value is returned. This method converts unicode values to str type under python 2. ''' try: value = conf[name] except KeyError: value = default return salt.utils.data.decode(value, to_str=True)
[ "def", "_config", "(", "name", ",", "conf", ",", "default", "=", "None", ")", ":", "try", ":", "value", "=", "conf", "[", "name", "]", "except", "KeyError", ":", "value", "=", "default", "return", "salt", ".", "utils", ".", "data", ".", "decode", "...
Return a value for 'name' from the config file options. If the 'name' is not in the config, the 'default' value is returned. This method converts unicode values to str type under python 2.
[ "Return", "a", "value", "for", "name", "from", "the", "config", "file", "options", ".", "If", "the", "name", "is", "not", "in", "the", "config", "the", "default", "value", "is", "returned", ".", "This", "method", "converts", "unicode", "values", "to", "s...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L166-L176
train
saltstack/salt
salt/pillar/pillar_ldap.py
_result_to_dict
def _result_to_dict(data, result, conf, source): ''' Aggregates LDAP search result based on rules, returns a dictionary. Rules: Attributes tagged in the pillar config as 'attrs' or 'lists' are scanned for a 'key=value' format (non matching entries are ignored. Entries matching the 'attrs' tag overwrite previous values where the key matches a previous result. Entries matching the 'lists' tag are appended to list of values where the key matches a previous result. All Matching entries are then written directly to the pillar data dictionary as data[key] = value. For example, search result: { saltKeyValue': ['ntpserver=ntp.acme.local', 'foo=myfoo'], 'saltList': ['vhost=www.acme.net', 'vhost=www.acme.local'] } is written to the pillar data dictionary as: { 'ntpserver': 'ntp.acme.local', 'foo': 'myfoo', 'vhost': ['www.acme.net', 'www.acme.local'] } ''' attrs = _config('attrs', conf) or [] lists = _config('lists', conf) or [] dict_key_attr = _config('dict_key_attr', conf) or 'dn' # TODO: # deprecate the default 'mode: split' and make the more # straightforward 'mode: map' the new default mode = _config('mode', conf) or 'split' if mode == 'map': data[source] = [] for record in result: ret = {} if 'dn' in attrs or 'distinguishedName' in attrs: log.debug('dn: %s', record[0]) ret['dn'] = record[0] record = record[1] log.debug('record: %s', record) for key in record: if key in attrs: for item in record.get(key): ret[key] = item if key in lists: ret[key] = record.get(key) data[source].append(ret) elif mode == 'dict': data[source] = {} for record in result: ret = {} distinguished_name = record[0] log.debug('dn: %s', distinguished_name) if 'dn' in attrs or 'distinguishedName' in attrs: ret['dn'] = distinguished_name record = record[1] log.debug('record: %s', record) for key in record: if key in attrs: for item in record.get(key): ret[key] = item if key in lists: ret[key] = record.get(key) if dict_key_attr in ['dn', 'distinguishedName']: dict_key = distinguished_name else: dict_key = ','.join(sorted(record.get(dict_key_attr, []))) try: data[source][dict_key].append(ret) except KeyError: data[source][dict_key] = [ret] elif mode == 'split': for key in result[0][1]: if key in attrs: for item in result.get(key): skey, sval = item.split('=', 1) data[skey] = sval elif key in lists: for item in result.get(key): if '=' in item: skey, sval = item.split('=', 1) if skey not in data: data[skey] = [sval] else: data[skey].append(sval) return data
python
def _result_to_dict(data, result, conf, source): ''' Aggregates LDAP search result based on rules, returns a dictionary. Rules: Attributes tagged in the pillar config as 'attrs' or 'lists' are scanned for a 'key=value' format (non matching entries are ignored. Entries matching the 'attrs' tag overwrite previous values where the key matches a previous result. Entries matching the 'lists' tag are appended to list of values where the key matches a previous result. All Matching entries are then written directly to the pillar data dictionary as data[key] = value. For example, search result: { saltKeyValue': ['ntpserver=ntp.acme.local', 'foo=myfoo'], 'saltList': ['vhost=www.acme.net', 'vhost=www.acme.local'] } is written to the pillar data dictionary as: { 'ntpserver': 'ntp.acme.local', 'foo': 'myfoo', 'vhost': ['www.acme.net', 'www.acme.local'] } ''' attrs = _config('attrs', conf) or [] lists = _config('lists', conf) or [] dict_key_attr = _config('dict_key_attr', conf) or 'dn' # TODO: # deprecate the default 'mode: split' and make the more # straightforward 'mode: map' the new default mode = _config('mode', conf) or 'split' if mode == 'map': data[source] = [] for record in result: ret = {} if 'dn' in attrs or 'distinguishedName' in attrs: log.debug('dn: %s', record[0]) ret['dn'] = record[0] record = record[1] log.debug('record: %s', record) for key in record: if key in attrs: for item in record.get(key): ret[key] = item if key in lists: ret[key] = record.get(key) data[source].append(ret) elif mode == 'dict': data[source] = {} for record in result: ret = {} distinguished_name = record[0] log.debug('dn: %s', distinguished_name) if 'dn' in attrs or 'distinguishedName' in attrs: ret['dn'] = distinguished_name record = record[1] log.debug('record: %s', record) for key in record: if key in attrs: for item in record.get(key): ret[key] = item if key in lists: ret[key] = record.get(key) if dict_key_attr in ['dn', 'distinguishedName']: dict_key = distinguished_name else: dict_key = ','.join(sorted(record.get(dict_key_attr, []))) try: data[source][dict_key].append(ret) except KeyError: data[source][dict_key] = [ret] elif mode == 'split': for key in result[0][1]: if key in attrs: for item in result.get(key): skey, sval = item.split('=', 1) data[skey] = sval elif key in lists: for item in result.get(key): if '=' in item: skey, sval = item.split('=', 1) if skey not in data: data[skey] = [sval] else: data[skey].append(sval) return data
[ "def", "_result_to_dict", "(", "data", ",", "result", ",", "conf", ",", "source", ")", ":", "attrs", "=", "_config", "(", "'attrs'", ",", "conf", ")", "or", "[", "]", "lists", "=", "_config", "(", "'lists'", ",", "conf", ")", "or", "[", "]", "dict_...
Aggregates LDAP search result based on rules, returns a dictionary. Rules: Attributes tagged in the pillar config as 'attrs' or 'lists' are scanned for a 'key=value' format (non matching entries are ignored. Entries matching the 'attrs' tag overwrite previous values where the key matches a previous result. Entries matching the 'lists' tag are appended to list of values where the key matches a previous result. All Matching entries are then written directly to the pillar data dictionary as data[key] = value. For example, search result: { saltKeyValue': ['ntpserver=ntp.acme.local', 'foo=myfoo'], 'saltList': ['vhost=www.acme.net', 'vhost=www.acme.local'] } is written to the pillar data dictionary as: { 'ntpserver': 'ntp.acme.local', 'foo': 'myfoo', 'vhost': ['www.acme.net', 'www.acme.local'] }
[ "Aggregates", "LDAP", "search", "result", "based", "on", "rules", "returns", "a", "dictionary", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L179-L267
train
saltstack/salt
salt/pillar/pillar_ldap.py
_do_search
def _do_search(conf): ''' Builds connection and search arguments, performs the LDAP search and formats the results as a dictionary appropriate for pillar use. ''' # Build LDAP connection args connargs = {} for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']: connargs[name] = _config(name, conf) if connargs['binddn'] and connargs['bindpw']: connargs['anonymous'] = False # Build search args try: _filter = conf['filter'] except KeyError: raise SaltInvocationError('missing filter') _dn = _config('dn', conf) scope = _config('scope', conf) _lists = _config('lists', conf) or [] _attrs = _config('attrs', conf) or [] _dict_key_attr = _config('dict_key_attr', conf, 'dn') attrs = _lists + _attrs + [_dict_key_attr] if not attrs: attrs = None # Perform the search try: result = __salt__['ldap.search'](_filter, _dn, scope, attrs, **connargs)['results'] except IndexError: # we got no results for this search log.debug('LDAP search returned no results for filter %s', _filter) result = {} except Exception: log.critical( 'Failed to retrieve pillar data from LDAP:\n', exc_info=True ) return {} return result
python
def _do_search(conf): ''' Builds connection and search arguments, performs the LDAP search and formats the results as a dictionary appropriate for pillar use. ''' # Build LDAP connection args connargs = {} for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']: connargs[name] = _config(name, conf) if connargs['binddn'] and connargs['bindpw']: connargs['anonymous'] = False # Build search args try: _filter = conf['filter'] except KeyError: raise SaltInvocationError('missing filter') _dn = _config('dn', conf) scope = _config('scope', conf) _lists = _config('lists', conf) or [] _attrs = _config('attrs', conf) or [] _dict_key_attr = _config('dict_key_attr', conf, 'dn') attrs = _lists + _attrs + [_dict_key_attr] if not attrs: attrs = None # Perform the search try: result = __salt__['ldap.search'](_filter, _dn, scope, attrs, **connargs)['results'] except IndexError: # we got no results for this search log.debug('LDAP search returned no results for filter %s', _filter) result = {} except Exception: log.critical( 'Failed to retrieve pillar data from LDAP:\n', exc_info=True ) return {} return result
[ "def", "_do_search", "(", "conf", ")", ":", "# Build LDAP connection args", "connargs", "=", "{", "}", "for", "name", "in", "[", "'server'", ",", "'port'", ",", "'tls'", ",", "'binddn'", ",", "'bindpw'", ",", "'anonymous'", "]", ":", "connargs", "[", "name...
Builds connection and search arguments, performs the LDAP search and formats the results as a dictionary appropriate for pillar use.
[ "Builds", "connection", "and", "search", "arguments", "performs", "the", "LDAP", "search", "and", "formats", "the", "results", "as", "a", "dictionary", "appropriate", "for", "pillar", "use", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L270-L306
train
saltstack/salt
salt/pillar/pillar_ldap.py
ext_pillar
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 config_file): ''' Execute LDAP searches and return the aggregated data ''' config_template = None try: config_template = _render_template(config_file) except jinja2.exceptions.TemplateNotFound: log.debug('pillar_ldap: missing configuration file %s', config_file) except Exception: log.debug('pillar_ldap: failed to render template for %s', config_file, exc_info=True) if not config_template: # We don't have a config file return {} import salt.utils.yaml try: opts = salt.utils.yaml.safe_load(config_template) or {} opts['conf_file'] = config_file except Exception as err: import salt.log msg = 'pillar_ldap: error parsing configuration file: {0} - {1}'.format( config_file, err ) if salt.log.is_console_configured(): log.warning(msg) else: print(msg) return {} else: if not isinstance(opts, dict): log.warning( 'pillar_ldap: %s is invalidly formatted, must be a YAML ' 'dictionary. See the documentation for more information.', config_file ) return {} if 'search_order' not in opts: log.warning( 'pillar_ldap: search_order missing from configuration. See the ' 'documentation for more information.' ) return {} data = {} for source in opts['search_order']: config = opts[source] result = _do_search(config) log.debug('source %s got result %s', source, result) if result: data = _result_to_dict(data, result, config, source) return data
python
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 config_file): ''' Execute LDAP searches and return the aggregated data ''' config_template = None try: config_template = _render_template(config_file) except jinja2.exceptions.TemplateNotFound: log.debug('pillar_ldap: missing configuration file %s', config_file) except Exception: log.debug('pillar_ldap: failed to render template for %s', config_file, exc_info=True) if not config_template: # We don't have a config file return {} import salt.utils.yaml try: opts = salt.utils.yaml.safe_load(config_template) or {} opts['conf_file'] = config_file except Exception as err: import salt.log msg = 'pillar_ldap: error parsing configuration file: {0} - {1}'.format( config_file, err ) if salt.log.is_console_configured(): log.warning(msg) else: print(msg) return {} else: if not isinstance(opts, dict): log.warning( 'pillar_ldap: %s is invalidly formatted, must be a YAML ' 'dictionary. See the documentation for more information.', config_file ) return {} if 'search_order' not in opts: log.warning( 'pillar_ldap: search_order missing from configuration. See the ' 'documentation for more information.' ) return {} data = {} for source in opts['search_order']: config = opts[source] result = _do_search(config) log.debug('source %s got result %s', source, result) if result: data = _result_to_dict(data, result, config, source) return data
[ "def", "ext_pillar", "(", "minion_id", ",", "# pylint: disable=W0613", "pillar", ",", "# pylint: disable=W0613", "config_file", ")", ":", "config_template", "=", "None", "try", ":", "config_template", "=", "_render_template", "(", "config_file", ")", "except", "jinja2...
Execute LDAP searches and return the aggregated data
[ "Execute", "LDAP", "searches", "and", "return", "the", "aggregated", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L309-L365
train
saltstack/salt
salt/states/win_pki.py
import_cert
def import_cert(name, cert_format=_DEFAULT_FORMAT, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE, exportable=True, password='', saltenv='base'): ''' Import the certificate file into the given certificate store. :param str name: The path of the certificate file to import. :param str cert_format: The certificate format. Specify 'cer' for X.509, or 'pfx' for PKCS #12. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. :param bool exportable: Mark the certificate as exportable. Only applicable to pfx format. :param str password: The password of the certificate. Only applicable to pfx format. :param str saltenv: The environment the file resides in. Example of usage with only the required arguments: .. code-block:: yaml site0-cert-imported: win_pki.import_cert: - name: salt://win/webserver/certs/site0.cer Example of usage specifying all available arguments: .. code-block:: yaml site0-cert-imported: win_pki.import_cert: - name: salt://win/webserver/certs/site0.pfx - cert_format: pfx - context: LocalMachine - store: My - exportable: True - password: TestPassword - saltenv: base ''' ret = {'name': name, 'changes': dict(), 'comment': six.text_type(), 'result': None} store_path = r'Cert:\{0}\{1}'.format(context, store) cached_source_path = __salt__['cp.cache_file'](name, saltenv) current_certs = __salt__['win_pki.get_certs'](context=context, store=store) if password: cert_props = __salt__['win_pki.get_cert_file'](name=cached_source_path, cert_format=cert_format, password=password) else: cert_props = __salt__['win_pki.get_cert_file'](name=cached_source_path, cert_format=cert_format) if cert_props['thumbprint'] in current_certs: ret['comment'] = ("Certificate '{0}' already contained in store:" ' {1}').format(cert_props['thumbprint'], store_path) ret['result'] = True elif __opts__['test']: ret['comment'] = ("Certificate '{0}' will be imported into store:" ' {1}').format(cert_props['thumbprint'], store_path) ret['changes'] = {'old': None, 'new': cert_props['thumbprint']} else: ret['changes'] = {'old': None, 'new': cert_props['thumbprint']} ret['result'] = __salt__['win_pki.import_cert'](name=name, cert_format=cert_format, context=context, store=store, exportable=exportable, password=password, saltenv=saltenv) if ret['result']: ret['comment'] = ("Certificate '{0}' imported into store:" ' {1}').format(cert_props['thumbprint'], store_path) else: ret['comment'] = ("Certificate '{0}' unable to be imported into store:" ' {1}').format(cert_props['thumbprint'], store_path) return ret
python
def import_cert(name, cert_format=_DEFAULT_FORMAT, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE, exportable=True, password='', saltenv='base'): ''' Import the certificate file into the given certificate store. :param str name: The path of the certificate file to import. :param str cert_format: The certificate format. Specify 'cer' for X.509, or 'pfx' for PKCS #12. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. :param bool exportable: Mark the certificate as exportable. Only applicable to pfx format. :param str password: The password of the certificate. Only applicable to pfx format. :param str saltenv: The environment the file resides in. Example of usage with only the required arguments: .. code-block:: yaml site0-cert-imported: win_pki.import_cert: - name: salt://win/webserver/certs/site0.cer Example of usage specifying all available arguments: .. code-block:: yaml site0-cert-imported: win_pki.import_cert: - name: salt://win/webserver/certs/site0.pfx - cert_format: pfx - context: LocalMachine - store: My - exportable: True - password: TestPassword - saltenv: base ''' ret = {'name': name, 'changes': dict(), 'comment': six.text_type(), 'result': None} store_path = r'Cert:\{0}\{1}'.format(context, store) cached_source_path = __salt__['cp.cache_file'](name, saltenv) current_certs = __salt__['win_pki.get_certs'](context=context, store=store) if password: cert_props = __salt__['win_pki.get_cert_file'](name=cached_source_path, cert_format=cert_format, password=password) else: cert_props = __salt__['win_pki.get_cert_file'](name=cached_source_path, cert_format=cert_format) if cert_props['thumbprint'] in current_certs: ret['comment'] = ("Certificate '{0}' already contained in store:" ' {1}').format(cert_props['thumbprint'], store_path) ret['result'] = True elif __opts__['test']: ret['comment'] = ("Certificate '{0}' will be imported into store:" ' {1}').format(cert_props['thumbprint'], store_path) ret['changes'] = {'old': None, 'new': cert_props['thumbprint']} else: ret['changes'] = {'old': None, 'new': cert_props['thumbprint']} ret['result'] = __salt__['win_pki.import_cert'](name=name, cert_format=cert_format, context=context, store=store, exportable=exportable, password=password, saltenv=saltenv) if ret['result']: ret['comment'] = ("Certificate '{0}' imported into store:" ' {1}').format(cert_props['thumbprint'], store_path) else: ret['comment'] = ("Certificate '{0}' unable to be imported into store:" ' {1}').format(cert_props['thumbprint'], store_path) return ret
[ "def", "import_cert", "(", "name", ",", "cert_format", "=", "_DEFAULT_FORMAT", ",", "context", "=", "_DEFAULT_CONTEXT", ",", "store", "=", "_DEFAULT_STORE", ",", "exportable", "=", "True", ",", "password", "=", "''", ",", "saltenv", "=", "'base'", ")", ":", ...
Import the certificate file into the given certificate store. :param str name: The path of the certificate file to import. :param str cert_format: The certificate format. Specify 'cer' for X.509, or 'pfx' for PKCS #12. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. :param bool exportable: Mark the certificate as exportable. Only applicable to pfx format. :param str password: The password of the certificate. Only applicable to pfx format. :param str saltenv: The environment the file resides in. Example of usage with only the required arguments: .. code-block:: yaml site0-cert-imported: win_pki.import_cert: - name: salt://win/webserver/certs/site0.cer Example of usage specifying all available arguments: .. code-block:: yaml site0-cert-imported: win_pki.import_cert: - name: salt://win/webserver/certs/site0.pfx - cert_format: pfx - context: LocalMachine - store: My - exportable: True - password: TestPassword - saltenv: base
[ "Import", "the", "certificate", "file", "into", "the", "given", "certificate", "store", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_pki.py#L30-L101
train
saltstack/salt
salt/states/win_pki.py
remove_cert
def remove_cert(name, thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE): ''' Remove the certificate from the given certificate store. :param str thumbprint: The thumbprint value of the target certificate. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. Example of usage with only the required arguments: .. code-block:: yaml site0-cert-removed: win_pki.remove_cert: - thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF Example of usage specifying all available arguments: .. code-block:: yaml site0-cert-removed: win_pki.remove_cert: - thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF - context: LocalMachine - store: My ''' ret = {'name': name, 'changes': dict(), 'comment': six.text_type(), 'result': None} store_path = r'Cert:\{0}\{1}'.format(context, store) current_certs = __salt__['win_pki.get_certs'](context=context, store=store) if thumbprint not in current_certs: ret['comment'] = "Certificate '{0}' already removed from store: {1}".format(thumbprint, store_path) ret['result'] = True elif __opts__['test']: ret['comment'] = "Certificate '{0}' will be removed from store: {1}".format(thumbprint, store_path) ret['changes'] = {'old': thumbprint, 'new': None} else: ret['changes'] = {'old': thumbprint, 'new': None} ret['result'] = __salt__['win_pki.remove_cert'](thumbprint=thumbprint, context=context, store=store) if ret['result']: ret['comment'] = "Certificate '{0}' removed from store: {1}".format(thumbprint, store_path) else: ret['comment'] = "Certificate '{0}' unable to be removed from store: {1}".format(thumbprint, store_path) return ret
python
def remove_cert(name, thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE): ''' Remove the certificate from the given certificate store. :param str thumbprint: The thumbprint value of the target certificate. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. Example of usage with only the required arguments: .. code-block:: yaml site0-cert-removed: win_pki.remove_cert: - thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF Example of usage specifying all available arguments: .. code-block:: yaml site0-cert-removed: win_pki.remove_cert: - thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF - context: LocalMachine - store: My ''' ret = {'name': name, 'changes': dict(), 'comment': six.text_type(), 'result': None} store_path = r'Cert:\{0}\{1}'.format(context, store) current_certs = __salt__['win_pki.get_certs'](context=context, store=store) if thumbprint not in current_certs: ret['comment'] = "Certificate '{0}' already removed from store: {1}".format(thumbprint, store_path) ret['result'] = True elif __opts__['test']: ret['comment'] = "Certificate '{0}' will be removed from store: {1}".format(thumbprint, store_path) ret['changes'] = {'old': thumbprint, 'new': None} else: ret['changes'] = {'old': thumbprint, 'new': None} ret['result'] = __salt__['win_pki.remove_cert'](thumbprint=thumbprint, context=context, store=store) if ret['result']: ret['comment'] = "Certificate '{0}' removed from store: {1}".format(thumbprint, store_path) else: ret['comment'] = "Certificate '{0}' unable to be removed from store: {1}".format(thumbprint, store_path) return ret
[ "def", "remove_cert", "(", "name", ",", "thumbprint", ",", "context", "=", "_DEFAULT_CONTEXT", ",", "store", "=", "_DEFAULT_STORE", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "dict", "(", ")", ",", "'comment'", ":", "six", ...
Remove the certificate from the given certificate store. :param str thumbprint: The thumbprint value of the target certificate. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. Example of usage with only the required arguments: .. code-block:: yaml site0-cert-removed: win_pki.remove_cert: - thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF Example of usage specifying all available arguments: .. code-block:: yaml site0-cert-removed: win_pki.remove_cert: - thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF - context: LocalMachine - store: My
[ "Remove", "the", "certificate", "from", "the", "given", "certificate", "store", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_pki.py#L104-L157
train
saltstack/salt
salt/sdb/etcd_db.py
set_
def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the etcd service ''' client = _get_conn(profile) client.set(key, value) return get(key, service, profile)
python
def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the etcd service ''' client = _get_conn(profile) client.set(key, value) return get(key, service, profile)
[ "def", "set_", "(", "key", ",", "value", ",", "service", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=W0613", "client", "=", "_get_conn", "(", "profile", ")", "client", ".", "set", "(", "key", ",", "value", ")", "return", "get...
Set a key/value pair in the etcd service
[ "Set", "a", "key", "/", "value", "pair", "in", "the", "etcd", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/etcd_db.py#L63-L69
train
saltstack/salt
salt/sdb/etcd_db.py
get
def get(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the etcd service ''' client = _get_conn(profile) result = client.get(key) return result.value
python
def get(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the etcd service ''' client = _get_conn(profile) result = client.get(key) return result.value
[ "def", "get", "(", "key", ",", "service", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=W0613", "client", "=", "_get_conn", "(", "profile", ")", "result", "=", "client", ".", "get", "(", "key", ")", "return", "result", ".", "va...
Get a value from the etcd service
[ "Get", "a", "value", "from", "the", "etcd", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/etcd_db.py#L72-L78
train
saltstack/salt
salt/sdb/etcd_db.py
delete
def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the etcd service ''' client = _get_conn(profile) try: client.delete(key) return True except Exception: return False
python
def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the etcd service ''' client = _get_conn(profile) try: client.delete(key) return True except Exception: return False
[ "def", "delete", "(", "key", ",", "service", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=W0613", "client", "=", "_get_conn", "(", "profile", ")", "try", ":", "client", ".", "delete", "(", "key", ")", "return", "True", "except",...
Get a value from the etcd service
[ "Get", "a", "value", "from", "the", "etcd", "service" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/etcd_db.py#L81-L90
train
saltstack/salt
salt/states/nftables.py
chain_present
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'): ''' .. versionadded:: 2014.7.0 Verify the chain is exist. name A user-defined chain name. table The table to own the chain. family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} chain_check = __salt__['nftables.check_chain'](table, name, family=family) if chain_check['result'] is True: ret['result'] = True ret['comment'] = ('nftables {0} chain is already exist in {1} table for {2}' .format(name, table, family)) return ret res = __salt__['nftables.new_chain']( table, name, table_type=table_type, hook=hook, priority=priority, family=family ) if res['result'] is True: ret['changes'] = {'locale': name} ret['result'] = True ret['comment'] = ('nftables {0} chain in {1} table create success for {2}' .format(name, table, family)) return ret else: ret['result'] = False ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format( name, table, res['comment'].strip(), family ) return ret
python
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'): ''' .. versionadded:: 2014.7.0 Verify the chain is exist. name A user-defined chain name. table The table to own the chain. family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} chain_check = __salt__['nftables.check_chain'](table, name, family=family) if chain_check['result'] is True: ret['result'] = True ret['comment'] = ('nftables {0} chain is already exist in {1} table for {2}' .format(name, table, family)) return ret res = __salt__['nftables.new_chain']( table, name, table_type=table_type, hook=hook, priority=priority, family=family ) if res['result'] is True: ret['changes'] = {'locale': name} ret['result'] = True ret['comment'] = ('nftables {0} chain in {1} table create success for {2}' .format(name, table, family)) return ret else: ret['result'] = False ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format( name, table, res['comment'].strip(), family ) return ret
[ "def", "chain_present", "(", "name", ",", "table", "=", "'filter'", ",", "table_type", "=", "None", ",", "hook", "=", "None", ",", "priority", "=", "None", ",", "family", "=", "'ipv4'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes...
.. versionadded:: 2014.7.0 Verify the chain is exist. name A user-defined chain name. table The table to own the chain. family Networking family, either ipv4 or ipv6
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nftables.py#L129-L180
train
saltstack/salt
salt/states/nftables.py
chain_absent
def chain_absent(name, table='filter', family='ipv4'): ''' .. versionadded:: 2014.7.0 Verify the chain is absent. family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} chain_check = __salt__['nftables.check_chain'](table, name, family) if not chain_check: ret['result'] = True ret['comment'] = ('nftables {0} chain is already absent in {1} table for {2}' .format(name, table, family)) return ret flush_chain = __salt__['nftables.flush'](table, name, family) if flush_chain: command = __salt__['nftables.delete_chain'](table, name, family) if command is True: ret['changes'] = {'locale': name} ret['result'] = True ret['comment'] = ('nftables {0} chain in {1} table delete success for {2}' .format(name, table, family)) else: ret['result'] = False ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}' .format(name, table, command.strip(), family)) else: ret['result'] = False ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format( name, table, flush_chain.strip(), family ) return ret
python
def chain_absent(name, table='filter', family='ipv4'): ''' .. versionadded:: 2014.7.0 Verify the chain is absent. family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} chain_check = __salt__['nftables.check_chain'](table, name, family) if not chain_check: ret['result'] = True ret['comment'] = ('nftables {0} chain is already absent in {1} table for {2}' .format(name, table, family)) return ret flush_chain = __salt__['nftables.flush'](table, name, family) if flush_chain: command = __salt__['nftables.delete_chain'](table, name, family) if command is True: ret['changes'] = {'locale': name} ret['result'] = True ret['comment'] = ('nftables {0} chain in {1} table delete success for {2}' .format(name, table, family)) else: ret['result'] = False ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}' .format(name, table, command.strip(), family)) else: ret['result'] = False ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format( name, table, flush_chain.strip(), family ) return ret
[ "def", "chain_absent", "(", "name", ",", "table", "=", "'filter'", ",", "family", "=", "'ipv4'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "cha...
.. versionadded:: 2014.7.0 Verify the chain is absent. family Networking family, either ipv4 or ipv6
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nftables.py#L183-L225
train
saltstack/salt
salt/states/nftables.py
append
def append(name, family='ipv4', **kwargs): ''' .. versionadded:: 0.17.0 Append a rule to a chain name A user-defined name to call this rule by in another part of a state or formula. This should not be an actual rule. family Network family, ipv4 or ipv6. All other arguments are passed in with the same name as the long option that would normally be used for nftables, with one exception: `--state` is specified as `connstate` instead of `state` (not to be confused with `ctstate`). ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} for ignore in _STATE_INTERNAL_KEYWORDS: if ignore in kwargs: del kwargs[ignore] res = __salt__['nftables.build_rule'](family=family, **kwargs) if not res['result']: return res rule = res['rule'] res = __salt__['nftables.build_rule'](full=True, family=family, command='add', **kwargs) if not res['result']: return res command = res['rule'] res = __salt__['nftables.check'](kwargs['table'], kwargs['chain'], rule, family) if res['result']: ret['result'] = True ret['comment'] = 'nftables rule for {0} already set ({1}) for {2}'.format( name, command.strip(), family) return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'nftables rule for {0} needs to be set ({1}) for {2}'.format( name, command.strip(), family) return ret res = __salt__['nftables.append'](kwargs['table'], kwargs['chain'], rule, family) if res['result']: ret['changes'] = {'locale': name} ret['result'] = True ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format( name, command.strip(), family) if 'save' in kwargs: if kwargs['save']: __salt__['nftables.save'](filename=None, family=family) ret['comment'] = ('Set and Saved nftables rule for {0} to: ' '{1} for {2}'.format(name, command.strip(), family)) return ret else: ret['result'] = False ret['comment'] = ('Failed to set nftables rule for {0}.\n' 'Attempted rule was {1} for {2}.\n' '{3}').format( name, command.strip(), family, res['comment']) return ret
python
def append(name, family='ipv4', **kwargs): ''' .. versionadded:: 0.17.0 Append a rule to a chain name A user-defined name to call this rule by in another part of a state or formula. This should not be an actual rule. family Network family, ipv4 or ipv6. All other arguments are passed in with the same name as the long option that would normally be used for nftables, with one exception: `--state` is specified as `connstate` instead of `state` (not to be confused with `ctstate`). ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} for ignore in _STATE_INTERNAL_KEYWORDS: if ignore in kwargs: del kwargs[ignore] res = __salt__['nftables.build_rule'](family=family, **kwargs) if not res['result']: return res rule = res['rule'] res = __salt__['nftables.build_rule'](full=True, family=family, command='add', **kwargs) if not res['result']: return res command = res['rule'] res = __salt__['nftables.check'](kwargs['table'], kwargs['chain'], rule, family) if res['result']: ret['result'] = True ret['comment'] = 'nftables rule for {0} already set ({1}) for {2}'.format( name, command.strip(), family) return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'nftables rule for {0} needs to be set ({1}) for {2}'.format( name, command.strip(), family) return ret res = __salt__['nftables.append'](kwargs['table'], kwargs['chain'], rule, family) if res['result']: ret['changes'] = {'locale': name} ret['result'] = True ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format( name, command.strip(), family) if 'save' in kwargs: if kwargs['save']: __salt__['nftables.save'](filename=None, family=family) ret['comment'] = ('Set and Saved nftables rule for {0} to: ' '{1} for {2}'.format(name, command.strip(), family)) return ret else: ret['result'] = False ret['comment'] = ('Failed to set nftables rule for {0}.\n' 'Attempted rule was {1} for {2}.\n' '{3}').format( name, command.strip(), family, res['comment']) return ret
[ "def", "append", "(", "name", ",", "family", "=", "'ipv4'", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "for", "ignore...
.. versionadded:: 0.17.0 Append a rule to a chain name A user-defined name to call this rule by in another part of a state or formula. This should not be an actual rule. family Network family, ipv4 or ipv6. All other arguments are passed in with the same name as the long option that would normally be used for nftables, with one exception: `--state` is specified as `connstate` instead of `state` (not to be confused with `ctstate`).
[ "..", "versionadded", "::", "0", ".", "17", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nftables.py#L228-L305
train
saltstack/salt
salt/states/nftables.py
flush
def flush(name, family='ipv4', **kwargs): ''' .. versionadded:: 2014.7.0 Flush current nftables state family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} for ignore in _STATE_INTERNAL_KEYWORDS: if ignore in kwargs: del kwargs[ignore] if 'table' not in kwargs: kwargs['table'] = 'filter' res = __salt__['nftables.check_table'](kwargs['table'], family=family) if not res['result']: ret['result'] = False ret['comment'] = 'Failed to flush table {0} in family {1}, table does not exist.'.format( kwargs['table'], family ) return ret if 'chain' not in kwargs: kwargs['chain'] = '' else: res = __salt__['nftables.check_chain'](kwargs['table'], kwargs['chain'], family=family) if not res['result']: ret['result'] = False ret['comment'] = 'Failed to flush chain {0} in table {1} in family {2}, chain does not exist.'.format( kwargs['chain'], kwargs['table'], family ) return ret res = __salt__['nftables.flush'](kwargs['table'], kwargs['chain'], family) if res['result']: ret['changes'] = {'locale': name} ret['result'] = True ret['comment'] = 'Flush nftables rules in {0} table {1} chain {2} family'.format( kwargs['table'], kwargs['chain'], family ) return ret else: ret['result'] = False ret['comment'] = 'Failed to flush nftables rules' return ret
python
def flush(name, family='ipv4', **kwargs): ''' .. versionadded:: 2014.7.0 Flush current nftables state family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} for ignore in _STATE_INTERNAL_KEYWORDS: if ignore in kwargs: del kwargs[ignore] if 'table' not in kwargs: kwargs['table'] = 'filter' res = __salt__['nftables.check_table'](kwargs['table'], family=family) if not res['result']: ret['result'] = False ret['comment'] = 'Failed to flush table {0} in family {1}, table does not exist.'.format( kwargs['table'], family ) return ret if 'chain' not in kwargs: kwargs['chain'] = '' else: res = __salt__['nftables.check_chain'](kwargs['table'], kwargs['chain'], family=family) if not res['result']: ret['result'] = False ret['comment'] = 'Failed to flush chain {0} in table {1} in family {2}, chain does not exist.'.format( kwargs['chain'], kwargs['table'], family ) return ret res = __salt__['nftables.flush'](kwargs['table'], kwargs['chain'], family) if res['result']: ret['changes'] = {'locale': name} ret['result'] = True ret['comment'] = 'Flush nftables rules in {0} table {1} chain {2} family'.format( kwargs['table'], kwargs['chain'], family ) return ret else: ret['result'] = False ret['comment'] = 'Failed to flush nftables rules' return ret
[ "def", "flush", "(", "name", ",", "family", "=", "'ipv4'", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "for", "ignore"...
.. versionadded:: 2014.7.0 Flush current nftables state family Networking family, either ipv4 or ipv6
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nftables.py#L480-L541
train
saltstack/salt
salt/modules/riak.py
__execute_cmd
def __execute_cmd(name, cmd): ''' Execute Riak commands ''' return __salt__['cmd.run_all']( '{0} {1}'.format(salt.utils.path.which(name), cmd) )
python
def __execute_cmd(name, cmd): ''' Execute Riak commands ''' return __salt__['cmd.run_all']( '{0} {1}'.format(salt.utils.path.which(name), cmd) )
[ "def", "__execute_cmd", "(", "name", ",", "cmd", ")", ":", "return", "__salt__", "[", "'cmd.run_all'", "]", "(", "'{0} {1}'", ".", "format", "(", "salt", ".", "utils", ".", "path", ".", "which", "(", "name", ")", ",", "cmd", ")", ")" ]
Execute Riak commands
[ "Execute", "Riak", "commands" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L20-L26
train
saltstack/salt
salt/modules/riak.py
start
def start(): ''' Start Riak CLI Example: .. code-block:: bash salt '*' riak.start ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak', 'start') if cmd['retcode'] != 0: ret['comment'] = cmd['stderr'] else: ret['comment'] = cmd['stdout'] ret['success'] = True return ret
python
def start(): ''' Start Riak CLI Example: .. code-block:: bash salt '*' riak.start ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak', 'start') if cmd['retcode'] != 0: ret['comment'] = cmd['stderr'] else: ret['comment'] = cmd['stdout'] ret['success'] = True return ret
[ "def", "start", "(", ")", ":", "ret", "=", "{", "'comment'", ":", "''", ",", "'success'", ":", "False", "}", "cmd", "=", "__execute_cmd", "(", "'riak'", ",", "'start'", ")", "if", "cmd", "[", "'retcode'", "]", "!=", "0", ":", "ret", "[", "'comment'...
Start Riak CLI Example: .. code-block:: bash salt '*' riak.start
[ "Start", "Riak" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L29-L49
train
saltstack/salt
salt/modules/riak.py
stop
def stop(): ''' Stop Riak .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.stop ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak', 'stop') if cmd['retcode'] != 0: ret['comment'] = cmd['stderr'] else: ret['comment'] = cmd['stdout'] ret['success'] = True return ret
python
def stop(): ''' Stop Riak .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.stop ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak', 'stop') if cmd['retcode'] != 0: ret['comment'] = cmd['stderr'] else: ret['comment'] = cmd['stdout'] ret['success'] = True return ret
[ "def", "stop", "(", ")", ":", "ret", "=", "{", "'comment'", ":", "''", ",", "'success'", ":", "False", "}", "cmd", "=", "__execute_cmd", "(", "'riak'", ",", "'stop'", ")", "if", "cmd", "[", "'retcode'", "]", "!=", "0", ":", "ret", "[", "'comment'",...
Stop Riak .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.stop
[ "Stop", "Riak" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L52-L74
train
saltstack/salt
salt/modules/riak.py
cluster_join
def cluster_join(username, hostname): ''' Join a Riak cluster .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_join <user> <host> username - The riak username to join the cluster hostname - The riak hostname you are connecting to ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd( 'riak-admin', 'cluster join {0}@{1}'.format(username, hostname) ) if cmd['retcode'] != 0: ret['comment'] = cmd['stdout'] else: ret['comment'] = cmd['stdout'] ret['success'] = True return ret
python
def cluster_join(username, hostname): ''' Join a Riak cluster .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_join <user> <host> username - The riak username to join the cluster hostname - The riak hostname you are connecting to ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd( 'riak-admin', 'cluster join {0}@{1}'.format(username, hostname) ) if cmd['retcode'] != 0: ret['comment'] = cmd['stdout'] else: ret['comment'] = cmd['stdout'] ret['success'] = True return ret
[ "def", "cluster_join", "(", "username", ",", "hostname", ")", ":", "ret", "=", "{", "'comment'", ":", "''", ",", "'success'", ":", "False", "}", "cmd", "=", "__execute_cmd", "(", "'riak-admin'", ",", "'cluster join {0}@{1}'", ".", "format", "(", "username", ...
Join a Riak cluster .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_join <user> <host> username - The riak username to join the cluster hostname - The riak hostname you are connecting to
[ "Join", "a", "Riak", "cluster" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L77-L104
train
saltstack/salt
salt/modules/riak.py
cluster_commit
def cluster_commit(): ''' Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak-admin', 'cluster commit') if cmd['retcode'] != 0: ret['comment'] = cmd['stdout'] else: ret['comment'] = cmd['stdout'] ret['success'] = True return ret
python
def cluster_commit(): ''' Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak-admin', 'cluster commit') if cmd['retcode'] != 0: ret['comment'] = cmd['stdout'] else: ret['comment'] = cmd['stdout'] ret['success'] = True return ret
[ "def", "cluster_commit", "(", ")", ":", "ret", "=", "{", "'comment'", ":", "''", ",", "'success'", ":", "False", "}", "cmd", "=", "__execute_cmd", "(", "'riak-admin'", ",", "'cluster commit'", ")", "if", "cmd", "[", "'retcode'", "]", "!=", "0", ":", "r...
Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit
[ "Commit", "Cluster", "Changes" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L157-L179
train
saltstack/salt
salt/modules/riak.py
member_status
def member_status(): ''' Get cluster member status .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.member_status ''' ret = {'membership': {}, 'summary': {'Valid': 0, 'Leaving': 0, 'Exiting': 0, 'Joining': 0, 'Down': 0, }} out = __execute_cmd('riak-admin', 'member-status')['stdout'].splitlines() for line in out: if line.startswith(('=', '-', 'Status')): continue if '/' in line: # We're in the summary line for item in line.split('/'): key, val = item.split(':') ret['summary'][key.strip()] = val.strip() if len(line.split()) == 4: # We're on a node status line (status, ring, pending, node) = line.split() ret['membership'][node] = { 'Status': status, 'Ring': ring, 'Pending': pending } return ret
python
def member_status(): ''' Get cluster member status .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.member_status ''' ret = {'membership': {}, 'summary': {'Valid': 0, 'Leaving': 0, 'Exiting': 0, 'Joining': 0, 'Down': 0, }} out = __execute_cmd('riak-admin', 'member-status')['stdout'].splitlines() for line in out: if line.startswith(('=', '-', 'Status')): continue if '/' in line: # We're in the summary line for item in line.split('/'): key, val = item.split(':') ret['summary'][key.strip()] = val.strip() if len(line.split()) == 4: # We're on a node status line (status, ring, pending, node) = line.split() ret['membership'][node] = { 'Status': status, 'Ring': ring, 'Pending': pending } return ret
[ "def", "member_status", "(", ")", ":", "ret", "=", "{", "'membership'", ":", "{", "}", ",", "'summary'", ":", "{", "'Valid'", ":", "0", ",", "'Leaving'", ":", "0", ",", "'Exiting'", ":", "0", ",", "'Joining'", ":", "0", ",", "'Down'", ":", "0", "...
Get cluster member status .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.member_status
[ "Get", "cluster", "member", "status" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L182-L223
train
saltstack/salt
salt/modules/riak.py
status
def status(): ''' Current node status .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.status ''' ret = {} cmd = __execute_cmd('riak-admin', 'status') for i in cmd['stdout'].splitlines(): if ':' in i: (name, val) = i.split(':', 1) ret[name.strip()] = val.strip() return ret
python
def status(): ''' Current node status .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.status ''' ret = {} cmd = __execute_cmd('riak-admin', 'status') for i in cmd['stdout'].splitlines(): if ':' in i: (name, val) = i.split(':', 1) ret[name.strip()] = val.strip() return ret
[ "def", "status", "(", ")", ":", "ret", "=", "{", "}", "cmd", "=", "__execute_cmd", "(", "'riak-admin'", ",", "'status'", ")", "for", "i", "in", "cmd", "[", "'stdout'", "]", ".", "splitlines", "(", ")", ":", "if", "':'", "in", "i", ":", "(", "name...
Current node status .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.status
[ "Current", "node", "status" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L226-L247
train
saltstack/salt
salt/states/portage_config.py
flags
def flags(name, use=None, accept_keywords=None, env=None, license=None, properties=None, unmask=False, mask=False): ''' Enforce the given flags on the given package or ``DEPEND`` atom. .. warning:: In most cases, the affected package(s) need to be rebuilt in order to apply the changes. name The name of the package or its DEPEND atom use A list of ``USE`` flags accept_keywords A list of keywords to accept. ``~ARCH`` means current host arch, and will be translated into a line without keywords env A list of environment files license A list of accepted licenses properties A list of additional properties unmask A boolean to unmask the package mask A boolean to mask the package ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} if use: result = _flags_helper('use', name, use, __opts__['test']) if result['result']: ret['changes']['use'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if accept_keywords: result = _flags_helper('accept_keywords', name, accept_keywords, __opts__['test']) if result['result']: ret['changes']['accept_keywords'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if env: result = _flags_helper('env', name, env, __opts__['test']) if result['result']: ret['changes']['env'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if license: result = _flags_helper('license', name, license, __opts__['test']) if result['result']: ret['changes']['license'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if properties: result = _flags_helper('properties', name, properties, __opts__['test']) if result['result']: ret['changes']['properties'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if mask: result = _mask_helper('mask', name, __opts__['test']) if result['result']: ret['changes']['mask'] = 'masked' elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if unmask: result = _mask_helper('unmask', name, __opts__['test']) if result['result']: ret['changes']['unmask'] = 'unmasked' elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if __opts__['test'] and not ret['result']: ret['result'] = None return ret
python
def flags(name, use=None, accept_keywords=None, env=None, license=None, properties=None, unmask=False, mask=False): ''' Enforce the given flags on the given package or ``DEPEND`` atom. .. warning:: In most cases, the affected package(s) need to be rebuilt in order to apply the changes. name The name of the package or its DEPEND atom use A list of ``USE`` flags accept_keywords A list of keywords to accept. ``~ARCH`` means current host arch, and will be translated into a line without keywords env A list of environment files license A list of accepted licenses properties A list of additional properties unmask A boolean to unmask the package mask A boolean to mask the package ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} if use: result = _flags_helper('use', name, use, __opts__['test']) if result['result']: ret['changes']['use'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if accept_keywords: result = _flags_helper('accept_keywords', name, accept_keywords, __opts__['test']) if result['result']: ret['changes']['accept_keywords'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if env: result = _flags_helper('env', name, env, __opts__['test']) if result['result']: ret['changes']['env'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if license: result = _flags_helper('license', name, license, __opts__['test']) if result['result']: ret['changes']['license'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if properties: result = _flags_helper('properties', name, properties, __opts__['test']) if result['result']: ret['changes']['properties'] = result['changes'] elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if mask: result = _mask_helper('mask', name, __opts__['test']) if result['result']: ret['changes']['mask'] = 'masked' elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if unmask: result = _mask_helper('unmask', name, __opts__['test']) if result['result']: ret['changes']['unmask'] = 'unmasked' elif result['result'] is False: ret['result'] = False ret['comment'] = result['comment'] return ret if __opts__['test'] and not ret['result']: ret['result'] = None return ret
[ "def", "flags", "(", "name", ",", "use", "=", "None", ",", "accept_keywords", "=", "None", ",", "env", "=", "None", ",", "license", "=", "None", ",", "properties", "=", "None", ",", "unmask", "=", "False", ",", "mask", "=", "False", ")", ":", "ret"...
Enforce the given flags on the given package or ``DEPEND`` atom. .. warning:: In most cases, the affected package(s) need to be rebuilt in order to apply the changes. name The name of the package or its DEPEND atom use A list of ``USE`` flags accept_keywords A list of keywords to accept. ``~ARCH`` means current host arch, and will be translated into a line without keywords env A list of environment files license A list of accepted licenses properties A list of additional properties unmask A boolean to unmask the package mask A boolean to mask the package
[ "Enforce", "the", "given", "flags", "on", "the", "given", "package", "or", "DEPEND", "atom", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/portage_config.py#L63-L168
train
saltstack/salt
salt/modules/webutil.py
useradd
def useradd(pwfile, user, password, opts='', runas=None): ''' Add a user to htpasswd file using the htpasswd command. If the htpasswd file does not exist, it will be created. pwfile Path to htpasswd file user User name password User password opts Valid options that can be passed are: - `n` Don't update file; display results on stdout. - `m` Force MD5 encryption of the password (default). - `d` Force CRYPT encryption of the password. - `p` Do not encrypt the password (plaintext). - `s` Force SHA encryption of the password. runas The system user to run htpasswd command with CLI Examples: .. code-block:: bash salt '*' webutil.useradd /etc/httpd/htpasswd larry badpassword salt '*' webutil.useradd /etc/httpd/htpasswd larry badpass opts=ns ''' if not os.path.exists(pwfile): opts += 'c' cmd = ['htpasswd', '-b{0}'.format(opts), pwfile, user, password] return __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
python
def useradd(pwfile, user, password, opts='', runas=None): ''' Add a user to htpasswd file using the htpasswd command. If the htpasswd file does not exist, it will be created. pwfile Path to htpasswd file user User name password User password opts Valid options that can be passed are: - `n` Don't update file; display results on stdout. - `m` Force MD5 encryption of the password (default). - `d` Force CRYPT encryption of the password. - `p` Do not encrypt the password (plaintext). - `s` Force SHA encryption of the password. runas The system user to run htpasswd command with CLI Examples: .. code-block:: bash salt '*' webutil.useradd /etc/httpd/htpasswd larry badpassword salt '*' webutil.useradd /etc/httpd/htpasswd larry badpass opts=ns ''' if not os.path.exists(pwfile): opts += 'c' cmd = ['htpasswd', '-b{0}'.format(opts), pwfile, user, password] return __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
[ "def", "useradd", "(", "pwfile", ",", "user", ",", "password", ",", "opts", "=", "''", ",", "runas", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "pwfile", ")", ":", "opts", "+=", "'c'", "cmd", "=", "[", "'htpasswd'"...
Add a user to htpasswd file using the htpasswd command. If the htpasswd file does not exist, it will be created. pwfile Path to htpasswd file user User name password User password opts Valid options that can be passed are: - `n` Don't update file; display results on stdout. - `m` Force MD5 encryption of the password (default). - `d` Force CRYPT encryption of the password. - `p` Do not encrypt the password (plaintext). - `s` Force SHA encryption of the password. runas The system user to run htpasswd command with CLI Examples: .. code-block:: bash salt '*' webutil.useradd /etc/httpd/htpasswd larry badpassword salt '*' webutil.useradd /etc/httpd/htpasswd larry badpass opts=ns
[ "Add", "a", "user", "to", "htpasswd", "file", "using", "the", "htpasswd", "command", ".", "If", "the", "htpasswd", "file", "does", "not", "exist", "it", "will", "be", "created", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/webutil.py#L33-L70
train
saltstack/salt
salt/modules/webutil.py
userdel
def userdel(pwfile, user, runas=None, all_results=False): ''' Delete a user from the specified htpasswd file. pwfile Path to htpasswd file user User name runas The system user to run htpasswd command with all_results Return stdout, stderr, and retcode, not just stdout CLI Examples: .. code-block:: bash salt '*' webutil.userdel /etc/httpd/htpasswd larry ''' if not os.path.exists(pwfile): return 'Error: The specified htpasswd file does not exist' cmd = ['htpasswd', '-D', pwfile, user] if all_results: out = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False) else: out = __salt__['cmd.run'](cmd, runas=runas, python_shell=False).splitlines() return out
python
def userdel(pwfile, user, runas=None, all_results=False): ''' Delete a user from the specified htpasswd file. pwfile Path to htpasswd file user User name runas The system user to run htpasswd command with all_results Return stdout, stderr, and retcode, not just stdout CLI Examples: .. code-block:: bash salt '*' webutil.userdel /etc/httpd/htpasswd larry ''' if not os.path.exists(pwfile): return 'Error: The specified htpasswd file does not exist' cmd = ['htpasswd', '-D', pwfile, user] if all_results: out = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False) else: out = __salt__['cmd.run'](cmd, runas=runas, python_shell=False).splitlines() return out
[ "def", "userdel", "(", "pwfile", ",", "user", ",", "runas", "=", "None", ",", "all_results", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "pwfile", ")", ":", "return", "'Error: The specified htpasswd file does not exist'", "cmd...
Delete a user from the specified htpasswd file. pwfile Path to htpasswd file user User name runas The system user to run htpasswd command with all_results Return stdout, stderr, and retcode, not just stdout CLI Examples: .. code-block:: bash salt '*' webutil.userdel /etc/httpd/htpasswd larry
[ "Delete", "a", "user", "from", "the", "specified", "htpasswd", "file", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/webutil.py#L73-L106
train
saltstack/salt
salt/modules/webutil.py
verify
def verify(pwfile, user, password, opts='', runas=None): ''' Return True if the htpasswd file exists, the user has an entry, and their password matches. pwfile Fully qualified path to htpasswd file user User name password User password opts Valid options that can be passed are: - `m` Force MD5 encryption of the password (default). - `d` Force CRYPT encryption of the password. - `p` Do not encrypt the password (plaintext). - `s` Force SHA encryption of the password. runas The system user to run htpasswd command with CLI Examples: .. code-block:: bash salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword opts=ns ''' if not os.path.exists(pwfile): return False cmd = ['htpasswd', '-bv{0}'.format(opts), pwfile, user, password] ret = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False) log.debug('Result of verifying htpasswd for user %s: %s', user, ret) return ret['retcode'] == 0
python
def verify(pwfile, user, password, opts='', runas=None): ''' Return True if the htpasswd file exists, the user has an entry, and their password matches. pwfile Fully qualified path to htpasswd file user User name password User password opts Valid options that can be passed are: - `m` Force MD5 encryption of the password (default). - `d` Force CRYPT encryption of the password. - `p` Do not encrypt the password (plaintext). - `s` Force SHA encryption of the password. runas The system user to run htpasswd command with CLI Examples: .. code-block:: bash salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword opts=ns ''' if not os.path.exists(pwfile): return False cmd = ['htpasswd', '-bv{0}'.format(opts), pwfile, user, password] ret = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False) log.debug('Result of verifying htpasswd for user %s: %s', user, ret) return ret['retcode'] == 0
[ "def", "verify", "(", "pwfile", ",", "user", ",", "password", ",", "opts", "=", "''", ",", "runas", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "pwfile", ")", ":", "return", "False", "cmd", "=", "[", "'htpasswd'", "...
Return True if the htpasswd file exists, the user has an entry, and their password matches. pwfile Fully qualified path to htpasswd file user User name password User password opts Valid options that can be passed are: - `m` Force MD5 encryption of the password (default). - `d` Force CRYPT encryption of the password. - `p` Do not encrypt the password (plaintext). - `s` Force SHA encryption of the password. runas The system user to run htpasswd command with CLI Examples: .. code-block:: bash salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword opts=ns
[ "Return", "True", "if", "the", "htpasswd", "file", "exists", "the", "user", "has", "an", "entry", "and", "their", "password", "matches", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/webutil.py#L109-L148
train
saltstack/salt
salt/utils/win_functions.py
is_admin
def is_admin(name): ''' Is the passed user a member of the Administrators group Args: name (str): The name to check Returns: bool: True if user is a member of the Administrators group, False otherwise ''' groups = get_user_groups(name, True) for group in groups: if group in ('S-1-5-32-544', 'S-1-5-18'): return True return False
python
def is_admin(name): ''' Is the passed user a member of the Administrators group Args: name (str): The name to check Returns: bool: True if user is a member of the Administrators group, False otherwise ''' groups = get_user_groups(name, True) for group in groups: if group in ('S-1-5-32-544', 'S-1-5-18'): return True return False
[ "def", "is_admin", "(", "name", ")", ":", "groups", "=", "get_user_groups", "(", "name", ",", "True", ")", "for", "group", "in", "groups", ":", "if", "group", "in", "(", "'S-1-5-32-544'", ",", "'S-1-5-18'", ")", ":", "return", "True", "return", "False" ]
Is the passed user a member of the Administrators group Args: name (str): The name to check Returns: bool: True if user is a member of the Administrators group, False otherwise
[ "Is", "the", "passed", "user", "a", "member", "of", "the", "Administrators", "group" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L51-L68
train
saltstack/salt
salt/utils/win_functions.py
get_user_groups
def get_user_groups(name, sid=False): ''' Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids ''' if name == 'SYSTEM': # 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'. groups = [name] else: groups = win32net.NetUserGetLocalGroups(None, name) if not sid: return groups ret_groups = set() for group in groups: ret_groups.add(get_sid_from_name(group)) return ret_groups
python
def get_user_groups(name, sid=False): ''' Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids ''' if name == 'SYSTEM': # 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'. groups = [name] else: groups = win32net.NetUserGetLocalGroups(None, name) if not sid: return groups ret_groups = set() for group in groups: ret_groups.add(get_sid_from_name(group)) return ret_groups
[ "def", "get_user_groups", "(", "name", ",", "sid", "=", "False", ")", ":", "if", "name", "==", "'SYSTEM'", ":", "# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.", "groups", "=", "[", "name", "]", "else", ":", "groups", "=", "win32net", ".", ...
Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids
[ "Get", "the", "groups", "to", "which", "a", "user", "belongs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L71-L96
train
saltstack/salt
salt/utils/win_functions.py
get_sid_from_name
def get_sid_from_name(name): ''' This is a tool for getting a sid from a name. The name can be any object. Usually a user or a group Args: name (str): The name of the user or group for which to get the sid Returns: str: The corresponding SID ''' # If None is passed, use the Universal Well-known SID "Null SID" if name is None: name = 'NULL SID' try: sid = win32security.LookupAccountName(None, name)[0] except pywintypes.error as exc: raise CommandExecutionError( 'User {0} not found: {1}'.format(name, exc)) return win32security.ConvertSidToStringSid(sid)
python
def get_sid_from_name(name): ''' This is a tool for getting a sid from a name. The name can be any object. Usually a user or a group Args: name (str): The name of the user or group for which to get the sid Returns: str: The corresponding SID ''' # If None is passed, use the Universal Well-known SID "Null SID" if name is None: name = 'NULL SID' try: sid = win32security.LookupAccountName(None, name)[0] except pywintypes.error as exc: raise CommandExecutionError( 'User {0} not found: {1}'.format(name, exc)) return win32security.ConvertSidToStringSid(sid)
[ "def", "get_sid_from_name", "(", "name", ")", ":", "# If None is passed, use the Universal Well-known SID \"Null SID\"", "if", "name", "is", "None", ":", "name", "=", "'NULL SID'", "try", ":", "sid", "=", "win32security", ".", "LookupAccountName", "(", "None", ",", ...
This is a tool for getting a sid from a name. The name can be any object. Usually a user or a group Args: name (str): The name of the user or group for which to get the sid Returns: str: The corresponding SID
[ "This", "is", "a", "tool", "for", "getting", "a", "sid", "from", "a", "name", ".", "The", "name", "can", "be", "any", "object", ".", "Usually", "a", "user", "or", "a", "group" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L99-L120
train
saltstack/salt
salt/utils/win_functions.py
get_current_user
def get_current_user(with_domain=True): ''' Gets the user executing the process Args: with_domain (bool): ``True`` will prepend the user name with the machine name or domain separated by a backslash Returns: str: The user name ''' try: user_name = win32api.GetUserNameEx(win32api.NameSamCompatible) if user_name[-1] == '$': # Make the system account easier to identify. # Fetch sid so as to handle other language than english test_user = win32api.GetUserName() if test_user == 'SYSTEM': user_name = 'SYSTEM' elif get_sid_from_name(test_user) == 'S-1-5-18': user_name = 'SYSTEM' elif not with_domain: user_name = win32api.GetUserName() except pywintypes.error as exc: raise CommandExecutionError( 'Failed to get current user: {0}'.format(exc)) if not user_name: return False return user_name
python
def get_current_user(with_domain=True): ''' Gets the user executing the process Args: with_domain (bool): ``True`` will prepend the user name with the machine name or domain separated by a backslash Returns: str: The user name ''' try: user_name = win32api.GetUserNameEx(win32api.NameSamCompatible) if user_name[-1] == '$': # Make the system account easier to identify. # Fetch sid so as to handle other language than english test_user = win32api.GetUserName() if test_user == 'SYSTEM': user_name = 'SYSTEM' elif get_sid_from_name(test_user) == 'S-1-5-18': user_name = 'SYSTEM' elif not with_domain: user_name = win32api.GetUserName() except pywintypes.error as exc: raise CommandExecutionError( 'Failed to get current user: {0}'.format(exc)) if not user_name: return False return user_name
[ "def", "get_current_user", "(", "with_domain", "=", "True", ")", ":", "try", ":", "user_name", "=", "win32api", ".", "GetUserNameEx", "(", "win32api", ".", "NameSamCompatible", ")", "if", "user_name", "[", "-", "1", "]", "==", "'$'", ":", "# Make the system ...
Gets the user executing the process Args: with_domain (bool): ``True`` will prepend the user name with the machine name or domain separated by a backslash Returns: str: The user name
[ "Gets", "the", "user", "executing", "the", "process" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L123-L155
train
saltstack/salt
salt/utils/win_functions.py
get_sam_name
def get_sam_name(username): r''' Gets the SAM name for a user. It basically prefixes a username without a backslash with the computer name. If the user does not exist, a SAM compatible name will be returned using the local hostname as the domain. i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator' .. note:: Long computer names are truncated to 15 characters ''' try: sid_obj = win32security.LookupAccountName(None, username)[0] except pywintypes.error: return '\\'.join([platform.node()[:15].upper(), username]) username, domain, _ = win32security.LookupAccountSid(None, sid_obj) return '\\'.join([domain, username])
python
def get_sam_name(username): r''' Gets the SAM name for a user. It basically prefixes a username without a backslash with the computer name. If the user does not exist, a SAM compatible name will be returned using the local hostname as the domain. i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator' .. note:: Long computer names are truncated to 15 characters ''' try: sid_obj = win32security.LookupAccountName(None, username)[0] except pywintypes.error: return '\\'.join([platform.node()[:15].upper(), username]) username, domain, _ = win32security.LookupAccountSid(None, sid_obj) return '\\'.join([domain, username])
[ "def", "get_sam_name", "(", "username", ")", ":", "try", ":", "sid_obj", "=", "win32security", ".", "LookupAccountName", "(", "None", ",", "username", ")", "[", "0", "]", "except", "pywintypes", ".", "error", ":", "return", "'\\\\'", ".", "join", "(", "[...
r''' Gets the SAM name for a user. It basically prefixes a username without a backslash with the computer name. If the user does not exist, a SAM compatible name will be returned using the local hostname as the domain. i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator' .. note:: Long computer names are truncated to 15 characters
[ "r", "Gets", "the", "SAM", "name", "for", "a", "user", ".", "It", "basically", "prefixes", "a", "username", "without", "a", "backslash", "with", "the", "computer", "name", ".", "If", "the", "user", "does", "not", "exist", "a", "SAM", "compatible", "name"...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L158-L173
train
saltstack/salt
salt/utils/win_functions.py
escape_argument
def escape_argument(arg, escape=True): ''' Escape the argument for the cmd.exe shell. See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx First we escape the quote chars to produce a argument suitable for CommandLineToArgvW. We don't need to do this for simple arguments. Args: arg (str): a single command line argument to escape for the cmd.exe shell Kwargs: escape (bool): True will call the escape_for_cmd_exe() function which escapes the characters '()%!^"<>&|'. False will not call the function and only quotes the cmd Returns: str: an escaped string suitable to be passed as a program argument to the cmd.exe shell ''' if not arg or re.search(r'(["\s])', arg): arg = '"' + arg.replace('"', r'\"') + '"' if not escape: return arg return escape_for_cmd_exe(arg)
python
def escape_argument(arg, escape=True): ''' Escape the argument for the cmd.exe shell. See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx First we escape the quote chars to produce a argument suitable for CommandLineToArgvW. We don't need to do this for simple arguments. Args: arg (str): a single command line argument to escape for the cmd.exe shell Kwargs: escape (bool): True will call the escape_for_cmd_exe() function which escapes the characters '()%!^"<>&|'. False will not call the function and only quotes the cmd Returns: str: an escaped string suitable to be passed as a program argument to the cmd.exe shell ''' if not arg or re.search(r'(["\s])', arg): arg = '"' + arg.replace('"', r'\"') + '"' if not escape: return arg return escape_for_cmd_exe(arg)
[ "def", "escape_argument", "(", "arg", ",", "escape", "=", "True", ")", ":", "if", "not", "arg", "or", "re", ".", "search", "(", "r'([\"\\s])'", ",", "arg", ")", ":", "arg", "=", "'\"'", "+", "arg", ".", "replace", "(", "'\"'", ",", "r'\\\"'", ")", ...
Escape the argument for the cmd.exe shell. See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx First we escape the quote chars to produce a argument suitable for CommandLineToArgvW. We don't need to do this for simple arguments. Args: arg (str): a single command line argument to escape for the cmd.exe shell Kwargs: escape (bool): True will call the escape_for_cmd_exe() function which escapes the characters '()%!^"<>&|'. False will not call the function and only quotes the cmd Returns: str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
[ "Escape", "the", "argument", "for", "the", "cmd", ".", "exe", "shell", ".", "See", "http", ":", "//", "blogs", ".", "msdn", ".", "com", "/", "b", "/", "twistylittlepassagesallalike", "/", "archive", "/", "2011", "/", "04", "/", "23", "/", "everyone", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L185-L209
train
saltstack/salt
salt/utils/win_functions.py
escape_for_cmd_exe
def escape_for_cmd_exe(arg): ''' Escape an argument string to be suitable to be passed to cmd.exe on Windows This method takes an argument that is expected to already be properly escaped for the receiving program to be properly parsed. This argument will be further escaped to pass the interpolation performed by cmd.exe unchanged. Any meta-characters will be escaped, removing the ability to e.g. use redirects or variables. Args: arg (str): a single command line argument to escape for cmd.exe Returns: str: an escaped string suitable to be passed as a program argument to cmd.exe ''' meta_chars = '()%!^"<>&|' meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')') meta_map = {char: "^{0}".format(char) for char in meta_chars} def escape_meta_chars(m): char = m.group(1) return meta_map[char] return meta_re.sub(escape_meta_chars, arg)
python
def escape_for_cmd_exe(arg): ''' Escape an argument string to be suitable to be passed to cmd.exe on Windows This method takes an argument that is expected to already be properly escaped for the receiving program to be properly parsed. This argument will be further escaped to pass the interpolation performed by cmd.exe unchanged. Any meta-characters will be escaped, removing the ability to e.g. use redirects or variables. Args: arg (str): a single command line argument to escape for cmd.exe Returns: str: an escaped string suitable to be passed as a program argument to cmd.exe ''' meta_chars = '()%!^"<>&|' meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')') meta_map = {char: "^{0}".format(char) for char in meta_chars} def escape_meta_chars(m): char = m.group(1) return meta_map[char] return meta_re.sub(escape_meta_chars, arg)
[ "def", "escape_for_cmd_exe", "(", "arg", ")", ":", "meta_chars", "=", "'()%!^\"<>&|'", "meta_re", "=", "re", ".", "compile", "(", "'('", "+", "'|'", ".", "join", "(", "re", ".", "escape", "(", "char", ")", "for", "char", "in", "list", "(", "meta_chars"...
Escape an argument string to be suitable to be passed to cmd.exe on Windows This method takes an argument that is expected to already be properly escaped for the receiving program to be properly parsed. This argument will be further escaped to pass the interpolation performed by cmd.exe unchanged. Any meta-characters will be escaped, removing the ability to e.g. use redirects or variables. Args: arg (str): a single command line argument to escape for cmd.exe Returns: str: an escaped string suitable to be passed as a program argument to cmd.exe
[ "Escape", "an", "argument", "string", "to", "be", "suitable", "to", "be", "passed", "to", "cmd", ".", "exe", "on", "Windows" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L212-L239
train
saltstack/salt
salt/utils/win_functions.py
broadcast_setting_change
def broadcast_setting_change(message='Environment'): ''' Send a WM_SETTINGCHANGE Broadcast to all Windows Args: message (str): A string value representing the portion of the system that has been updated and needs to be refreshed. Default is ``Environment``. These are some common values: - "Environment" : to effect a change in the environment variables - "intl" : to effect a change in locale settings - "Policy" : to effect a change in Group Policy Settings - a leaf node in the registry - the name of a section in the ``Win.ini`` file See lParam within msdn docs for `WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_ for more information on Broadcasting Messages. See GWL_WNDPROC within msdn docs for `SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_ for information on how to retrieve those messages. .. note:: This will only affect new processes that aren't launched by services. To apply changes to the path or registry to services, the host must be restarted. The ``salt-minion``, if running as a service, will not see changes to the environment until the system is restarted. Services inherit their environment from ``services.exe`` which does not respond to messaging events. See `MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_ for more information. CLI Example: ... code-block:: python import salt.utils.win_functions salt.utils.win_functions.broadcast_setting_change('Environment') ''' # Listen for messages sent by this would involve working with the # SetWindowLong function. This can be accessed via win32gui or through # ctypes. You can find examples on how to do this by searching for # `Accessing WGL_WNDPROC` on the internet. Here are some examples of how # this might work: # # # using win32gui # import win32con # import win32gui # old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function) # # # using ctypes # import ctypes # import win32con # from ctypes import c_long, c_int # user32 = ctypes.WinDLL('user32', use_last_error=True) # WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int) # new_function = WndProcType # old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function) broadcast_message = ctypes.create_unicode_buffer(message) user32 = ctypes.WinDLL('user32', use_last_error=True) result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, broadcast_message, SMTO_ABORTIFHUNG, 5000, 0) return result == 1
python
def broadcast_setting_change(message='Environment'): ''' Send a WM_SETTINGCHANGE Broadcast to all Windows Args: message (str): A string value representing the portion of the system that has been updated and needs to be refreshed. Default is ``Environment``. These are some common values: - "Environment" : to effect a change in the environment variables - "intl" : to effect a change in locale settings - "Policy" : to effect a change in Group Policy Settings - a leaf node in the registry - the name of a section in the ``Win.ini`` file See lParam within msdn docs for `WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_ for more information on Broadcasting Messages. See GWL_WNDPROC within msdn docs for `SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_ for information on how to retrieve those messages. .. note:: This will only affect new processes that aren't launched by services. To apply changes to the path or registry to services, the host must be restarted. The ``salt-minion``, if running as a service, will not see changes to the environment until the system is restarted. Services inherit their environment from ``services.exe`` which does not respond to messaging events. See `MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_ for more information. CLI Example: ... code-block:: python import salt.utils.win_functions salt.utils.win_functions.broadcast_setting_change('Environment') ''' # Listen for messages sent by this would involve working with the # SetWindowLong function. This can be accessed via win32gui or through # ctypes. You can find examples on how to do this by searching for # `Accessing WGL_WNDPROC` on the internet. Here are some examples of how # this might work: # # # using win32gui # import win32con # import win32gui # old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function) # # # using ctypes # import ctypes # import win32con # from ctypes import c_long, c_int # user32 = ctypes.WinDLL('user32', use_last_error=True) # WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int) # new_function = WndProcType # old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function) broadcast_message = ctypes.create_unicode_buffer(message) user32 = ctypes.WinDLL('user32', use_last_error=True) result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, broadcast_message, SMTO_ABORTIFHUNG, 5000, 0) return result == 1
[ "def", "broadcast_setting_change", "(", "message", "=", "'Environment'", ")", ":", "# Listen for messages sent by this would involve working with the", "# SetWindowLong function. This can be accessed via win32gui or through", "# ctypes. You can find examples on how to do this by searching for", ...
Send a WM_SETTINGCHANGE Broadcast to all Windows Args: message (str): A string value representing the portion of the system that has been updated and needs to be refreshed. Default is ``Environment``. These are some common values: - "Environment" : to effect a change in the environment variables - "intl" : to effect a change in locale settings - "Policy" : to effect a change in Group Policy Settings - a leaf node in the registry - the name of a section in the ``Win.ini`` file See lParam within msdn docs for `WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_ for more information on Broadcasting Messages. See GWL_WNDPROC within msdn docs for `SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_ for information on how to retrieve those messages. .. note:: This will only affect new processes that aren't launched by services. To apply changes to the path or registry to services, the host must be restarted. The ``salt-minion``, if running as a service, will not see changes to the environment until the system is restarted. Services inherit their environment from ``services.exe`` which does not respond to messaging events. See `MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_ for more information. CLI Example: ... code-block:: python import salt.utils.win_functions salt.utils.win_functions.broadcast_setting_change('Environment')
[ "Send", "a", "WM_SETTINGCHANGE", "Broadcast", "to", "all", "Windows" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L242-L308
train
saltstack/salt
salt/utils/win_functions.py
guid_to_squid
def guid_to_squid(guid): ''' Converts a GUID to a compressed guid (SQUID) Each Guid has 5 parts separated by '-'. For the first three each one will be totally reversed, and for the remaining two each one will be reversed by every other character. Then the final compressed Guid will be constructed by concatenating all the reversed parts without '-'. .. Example:: Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94 Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49 Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49 Args: guid (str): A valid GUID Returns: str: A valid compressed GUID (SQUID) ''' guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$') guid_match = guid_pattern.match(guid) squid = '' if guid_match is not None: for index in range(1, 12): squid += guid_match.group(index)[::-1] return squid
python
def guid_to_squid(guid): ''' Converts a GUID to a compressed guid (SQUID) Each Guid has 5 parts separated by '-'. For the first three each one will be totally reversed, and for the remaining two each one will be reversed by every other character. Then the final compressed Guid will be constructed by concatenating all the reversed parts without '-'. .. Example:: Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94 Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49 Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49 Args: guid (str): A valid GUID Returns: str: A valid compressed GUID (SQUID) ''' guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$') guid_match = guid_pattern.match(guid) squid = '' if guid_match is not None: for index in range(1, 12): squid += guid_match.group(index)[::-1] return squid
[ "def", "guid_to_squid", "(", "guid", ")", ":", "guid_pattern", "=", "re", ".", "compile", "(", "r'^\\{(\\w{8})-(\\w{4})-(\\w{4})-(\\w\\w)(\\w\\w)-(\\w\\w)(\\w\\w)(\\w\\w)(\\w\\w)(\\w\\w)(\\w\\w)\\}$'", ")", "guid_match", "=", "guid_pattern", ".", "match", "(", "guid", ")", ...
Converts a GUID to a compressed guid (SQUID) Each Guid has 5 parts separated by '-'. For the first three each one will be totally reversed, and for the remaining two each one will be reversed by every other character. Then the final compressed Guid will be constructed by concatenating all the reversed parts without '-'. .. Example:: Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94 Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49 Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49 Args: guid (str): A valid GUID Returns: str: A valid compressed GUID (SQUID)
[ "Converts", "a", "GUID", "to", "a", "compressed", "guid", "(", "SQUID", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L311-L339
train
saltstack/salt
salt/utils/win_functions.py
squid_to_guid
def squid_to_guid(squid): ''' Converts a compressed GUID (SQUID) back into a GUID Args: squid (str): A valid compressed GUID Returns: str: A valid GUID ''' squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$') squid_match = squid_pattern.match(squid) guid = '' if squid_match is not None: guid = '{' + \ squid_match.group(1)[::-1]+'-' + \ squid_match.group(2)[::-1]+'-' + \ squid_match.group(3)[::-1]+'-' + \ squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-' for index in range(6, 12): guid += squid_match.group(index)[::-1] guid += '}' return guid
python
def squid_to_guid(squid): ''' Converts a compressed GUID (SQUID) back into a GUID Args: squid (str): A valid compressed GUID Returns: str: A valid GUID ''' squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$') squid_match = squid_pattern.match(squid) guid = '' if squid_match is not None: guid = '{' + \ squid_match.group(1)[::-1]+'-' + \ squid_match.group(2)[::-1]+'-' + \ squid_match.group(3)[::-1]+'-' + \ squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-' for index in range(6, 12): guid += squid_match.group(index)[::-1] guid += '}' return guid
[ "def", "squid_to_guid", "(", "squid", ")", ":", "squid_pattern", "=", "re", ".", "compile", "(", "r'^(\\w{8})(\\w{4})(\\w{4})(\\w\\w)(\\w\\w)(\\w\\w)(\\w\\w)(\\w\\w)(\\w\\w)(\\w\\w)(\\w\\w)$'", ")", "squid_match", "=", "squid_pattern", ".", "match", "(", "squid", ")", "gu...
Converts a compressed GUID (SQUID) back into a GUID Args: squid (str): A valid compressed GUID Returns: str: A valid GUID
[ "Converts", "a", "compressed", "GUID", "(", "SQUID", ")", "back", "into", "a", "GUID" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L342-L365
train
saltstack/salt
salt/runners/mine.py
get
def get(tgt, fun, tgt_type='glob'): ''' Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type CLI Example: .. code-block:: bash salt-run mine.get '*' network.interfaces ''' ret = salt.utils.minions.mine_get(tgt, fun, tgt_type, __opts__) return ret
python
def get(tgt, fun, tgt_type='glob'): ''' Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type CLI Example: .. code-block:: bash salt-run mine.get '*' network.interfaces ''' ret = salt.utils.minions.mine_get(tgt, fun, tgt_type, __opts__) return ret
[ "def", "get", "(", "tgt", ",", "fun", ",", "tgt_type", "=", "'glob'", ")", ":", "ret", "=", "salt", ".", "utils", ".", "minions", ".", "mine_get", "(", "tgt", ",", "fun", ",", "tgt_type", ",", "__opts__", ")", "return", "ret" ]
Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type CLI Example: .. code-block:: bash salt-run mine.get '*' network.interfaces
[ "Gathers", "the", "data", "from", "the", "specified", "minions", "mine", "pass", "in", "the", "target", "function", "to", "look", "up", "and", "the", "target", "type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/mine.py#L16-L28
train
saltstack/salt
salt/runners/mine.py
update
def update(tgt, tgt_type='glob', clear=False, mine_functions=None): ''' .. versionadded:: 2017.7.0 Update the mine data on a certain group of minions. tgt Which minions to target for the execution. tgt_type: ``glob`` The type of ``tgt``. clear: ``False`` Boolean flag specifying whether updating will clear the existing mines, or will update. Default: ``False`` (update). mine_functions Update the mine data on certain functions only. This feature can be used when updating the mine for functions that require refresh at different intervals than the rest of the functions specified under ``mine_functions`` in the minion/master config or pillar. CLI Example: .. code-block:: bash salt-run mine.update '*' salt-run mine.update 'juniper-edges' tgt_type='nodegroup' ''' ret = __salt__['salt.execute'](tgt, 'mine.update', tgt_type=tgt_type, clear=clear, mine_functions=mine_functions) return ret
python
def update(tgt, tgt_type='glob', clear=False, mine_functions=None): ''' .. versionadded:: 2017.7.0 Update the mine data on a certain group of minions. tgt Which minions to target for the execution. tgt_type: ``glob`` The type of ``tgt``. clear: ``False`` Boolean flag specifying whether updating will clear the existing mines, or will update. Default: ``False`` (update). mine_functions Update the mine data on certain functions only. This feature can be used when updating the mine for functions that require refresh at different intervals than the rest of the functions specified under ``mine_functions`` in the minion/master config or pillar. CLI Example: .. code-block:: bash salt-run mine.update '*' salt-run mine.update 'juniper-edges' tgt_type='nodegroup' ''' ret = __salt__['salt.execute'](tgt, 'mine.update', tgt_type=tgt_type, clear=clear, mine_functions=mine_functions) return ret
[ "def", "update", "(", "tgt", ",", "tgt_type", "=", "'glob'", ",", "clear", "=", "False", ",", "mine_functions", "=", "None", ")", ":", "ret", "=", "__salt__", "[", "'salt.execute'", "]", "(", "tgt", ",", "'mine.update'", ",", "tgt_type", "=", "tgt_type",...
.. versionadded:: 2017.7.0 Update the mine data on a certain group of minions. tgt Which minions to target for the execution. tgt_type: ``glob`` The type of ``tgt``. clear: ``False`` Boolean flag specifying whether updating will clear the existing mines, or will update. Default: ``False`` (update). mine_functions Update the mine data on certain functions only. This feature can be used when updating the mine for functions that require refresh at different intervals than the rest of the functions specified under ``mine_functions`` in the minion/master config or pillar. CLI Example: .. code-block:: bash salt-run mine.update '*' salt-run mine.update 'juniper-edges' tgt_type='nodegroup'
[ "..", "versionadded", "::", "2017", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/mine.py#L31-L69
train
saltstack/salt
salt/utils/nxos.py
nxapi_request
def nxapi_request(commands, method='cli_show', **kwargs): ''' Send exec and config commands to the NX-OS device over NX-API. commands The exec or config commands to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show``. transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``http``, and ``https``. host: ``localhost`` The IP address or DNS host name of the device. username: ``admin`` The username to pass to the device to authenticate the NX-API connection. password The password to pass to the device to authenticate the NX-API connection. port The TCP port of the endpoint for the NX-API connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). timeout: ``60`` Time in seconds to wait for the device to respond. Default: 60 seconds. verify: ``True`` Either a boolean, in which case it controls whether we verify the NX-API TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. ''' client = NxapiClient(**kwargs) return client.request(method, commands)
python
def nxapi_request(commands, method='cli_show', **kwargs): ''' Send exec and config commands to the NX-OS device over NX-API. commands The exec or config commands to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show``. transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``http``, and ``https``. host: ``localhost`` The IP address or DNS host name of the device. username: ``admin`` The username to pass to the device to authenticate the NX-API connection. password The password to pass to the device to authenticate the NX-API connection. port The TCP port of the endpoint for the NX-API connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). timeout: ``60`` Time in seconds to wait for the device to respond. Default: 60 seconds. verify: ``True`` Either a boolean, in which case it controls whether we verify the NX-API TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. ''' client = NxapiClient(**kwargs) return client.request(method, commands)
[ "def", "nxapi_request", "(", "commands", ",", "method", "=", "'cli_show'", ",", "*", "*", "kwargs", ")", ":", "client", "=", "NxapiClient", "(", "*", "*", "kwargs", ")", "return", "client", ".", "request", "(", "method", ",", "commands", ")" ]
Send exec and config commands to the NX-OS device over NX-API. commands The exec or config commands to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. Defaults to ``cli_show``. transport: ``https`` Specifies the type of connection transport to use. Valid values for the connection are ``http``, and ``https``. host: ``localhost`` The IP address or DNS host name of the device. username: ``admin`` The username to pass to the device to authenticate the NX-API connection. password The password to pass to the device to authenticate the NX-API connection. port The TCP port of the endpoint for the NX-API connection. If this keyword is not specified, the default value is automatically determined by the transport type (``80`` for ``http``, or ``443`` for ``https``). timeout: ``60`` Time in seconds to wait for the device to respond. Default: 60 seconds. verify: ``True`` Either a boolean, in which case it controls whether we verify the NX-API TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``.
[ "Send", "exec", "and", "config", "commands", "to", "the", "NX", "-", "OS", "device", "over", "NX", "-", "API", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L271-L313
train
saltstack/salt
salt/utils/nxos.py
system_info
def system_info(data): ''' Helper method to return parsed system_info from the 'show version' command. ''' if not data: return {} info = { 'software': _parse_software(data), 'hardware': _parse_hardware(data), 'plugins': _parse_plugins(data), } return {'nxos': info}
python
def system_info(data): ''' Helper method to return parsed system_info from the 'show version' command. ''' if not data: return {} info = { 'software': _parse_software(data), 'hardware': _parse_hardware(data), 'plugins': _parse_plugins(data), } return {'nxos': info}
[ "def", "system_info", "(", "data", ")", ":", "if", "not", "data", ":", "return", "{", "}", "info", "=", "{", "'software'", ":", "_parse_software", "(", "data", ")", ",", "'hardware'", ":", "_parse_hardware", "(", "data", ")", ",", "'plugins'", ":", "_p...
Helper method to return parsed system_info from the 'show version' command.
[ "Helper", "method", "to", "return", "parsed", "system_info", "from", "the", "show", "version", "command", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L372-L384
train
saltstack/salt
salt/utils/nxos.py
NxapiClient._use_remote_connection
def _use_remote_connection(self, kwargs): ''' Determine if connection is local or remote ''' kwargs['host'] = kwargs.get('host') kwargs['username'] = kwargs.get('username') kwargs['password'] = kwargs.get('password') if kwargs['host'] is None or \ kwargs['username'] is None or \ kwargs['password'] is None: return False else: return True
python
def _use_remote_connection(self, kwargs): ''' Determine if connection is local or remote ''' kwargs['host'] = kwargs.get('host') kwargs['username'] = kwargs.get('username') kwargs['password'] = kwargs.get('password') if kwargs['host'] is None or \ kwargs['username'] is None or \ kwargs['password'] is None: return False else: return True
[ "def", "_use_remote_connection", "(", "self", ",", "kwargs", ")", ":", "kwargs", "[", "'host'", "]", "=", "kwargs", ".", "get", "(", "'host'", ")", "kwargs", "[", "'username'", "]", "=", "kwargs", ".", "get", "(", "'username'", ")", "kwargs", "[", "'pa...
Determine if connection is local or remote
[ "Determine", "if", "connection", "is", "local", "or", "remote" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L107-L119
train
saltstack/salt
salt/utils/nxos.py
NxapiClient._prepare_conn_args
def _prepare_conn_args(self, kwargs): ''' Set connection arguments for remote or local connection. ''' kwargs['connect_over_uds'] = True kwargs['timeout'] = kwargs.get('timeout', 60) kwargs['cookie'] = kwargs.get('cookie', 'admin') if self._use_remote_connection(kwargs): kwargs['transport'] = kwargs.get('transport', 'https') if kwargs['transport'] == 'https': kwargs['port'] = kwargs.get('port', 443) else: kwargs['port'] = kwargs.get('port', 80) kwargs['verify'] = kwargs.get('verify', True) if isinstance(kwargs['verify'], bool): kwargs['verify_ssl'] = kwargs['verify'] else: kwargs['ca_bundle'] = kwargs['verify'] kwargs['connect_over_uds'] = False return kwargs
python
def _prepare_conn_args(self, kwargs): ''' Set connection arguments for remote or local connection. ''' kwargs['connect_over_uds'] = True kwargs['timeout'] = kwargs.get('timeout', 60) kwargs['cookie'] = kwargs.get('cookie', 'admin') if self._use_remote_connection(kwargs): kwargs['transport'] = kwargs.get('transport', 'https') if kwargs['transport'] == 'https': kwargs['port'] = kwargs.get('port', 443) else: kwargs['port'] = kwargs.get('port', 80) kwargs['verify'] = kwargs.get('verify', True) if isinstance(kwargs['verify'], bool): kwargs['verify_ssl'] = kwargs['verify'] else: kwargs['ca_bundle'] = kwargs['verify'] kwargs['connect_over_uds'] = False return kwargs
[ "def", "_prepare_conn_args", "(", "self", ",", "kwargs", ")", ":", "kwargs", "[", "'connect_over_uds'", "]", "=", "True", "kwargs", "[", "'timeout'", "]", "=", "kwargs", ".", "get", "(", "'timeout'", ",", "60", ")", "kwargs", "[", "'cookie'", "]", "=", ...
Set connection arguments for remote or local connection.
[ "Set", "connection", "arguments", "for", "remote", "or", "local", "connection", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L121-L140
train
saltstack/salt
salt/utils/nxos.py
NxapiClient._build_request
def _build_request(self, type, commands): ''' Build NX-API JSON request. ''' request = {} headers = { 'content-type': 'application/json', } if self.nxargs['connect_over_uds']: user = self.nxargs['cookie'] headers['cookie'] = 'nxapi_auth=' + user + ':local' request['url'] = self.NXAPI_UDS_URI_PATH else: request['url'] = '{transport}://{host}:{port}{uri}'.format( transport=self.nxargs['transport'], host=self.nxargs['host'], port=self.nxargs['port'], uri=self.NXAPI_REMOTE_URI_PATH, ) if isinstance(commands, (list, set, tuple)): commands = ' ; '.join(commands) payload = {} payload['ins_api'] = { 'version': self.NXAPI_VERSION, 'type': type, 'chunk': '0', 'sid': '1', 'input': commands, 'output_format': 'json', } request['headers'] = headers request['payload'] = json.dumps(payload) request['opts'] = { 'http_request_timeout': self.nxargs['timeout'] } log.info('request: %s', request) return request
python
def _build_request(self, type, commands): ''' Build NX-API JSON request. ''' request = {} headers = { 'content-type': 'application/json', } if self.nxargs['connect_over_uds']: user = self.nxargs['cookie'] headers['cookie'] = 'nxapi_auth=' + user + ':local' request['url'] = self.NXAPI_UDS_URI_PATH else: request['url'] = '{transport}://{host}:{port}{uri}'.format( transport=self.nxargs['transport'], host=self.nxargs['host'], port=self.nxargs['port'], uri=self.NXAPI_REMOTE_URI_PATH, ) if isinstance(commands, (list, set, tuple)): commands = ' ; '.join(commands) payload = {} payload['ins_api'] = { 'version': self.NXAPI_VERSION, 'type': type, 'chunk': '0', 'sid': '1', 'input': commands, 'output_format': 'json', } request['headers'] = headers request['payload'] = json.dumps(payload) request['opts'] = { 'http_request_timeout': self.nxargs['timeout'] } log.info('request: %s', request) return request
[ "def", "_build_request", "(", "self", ",", "type", ",", "commands", ")", ":", "request", "=", "{", "}", "headers", "=", "{", "'content-type'", ":", "'application/json'", ",", "}", "if", "self", ".", "nxargs", "[", "'connect_over_uds'", "]", ":", "user", ...
Build NX-API JSON request.
[ "Build", "NX", "-", "API", "JSON", "request", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L142-L179
train
saltstack/salt
salt/utils/nxos.py
NxapiClient.request
def request(self, type, command_list): ''' Send NX-API JSON request to the NX-OS device. ''' req = self._build_request(type, command_list) if self.nxargs['connect_over_uds']: self.connection.request('POST', req['url'], req['payload'], req['headers']) response = self.connection.getresponse() else: response = self.connection(req['url'], method='POST', opts=req['opts'], data=req['payload'], header_dict=req['headers'], decode=True, decode_type='json', **self.nxargs) return self.parse_response(response, command_list)
python
def request(self, type, command_list): ''' Send NX-API JSON request to the NX-OS device. ''' req = self._build_request(type, command_list) if self.nxargs['connect_over_uds']: self.connection.request('POST', req['url'], req['payload'], req['headers']) response = self.connection.getresponse() else: response = self.connection(req['url'], method='POST', opts=req['opts'], data=req['payload'], header_dict=req['headers'], decode=True, decode_type='json', **self.nxargs) return self.parse_response(response, command_list)
[ "def", "request", "(", "self", ",", "type", ",", "command_list", ")", ":", "req", "=", "self", ".", "_build_request", "(", "type", ",", "command_list", ")", "if", "self", ".", "nxargs", "[", "'connect_over_uds'", "]", ":", "self", ".", "connection", ".",...
Send NX-API JSON request to the NX-OS device.
[ "Send", "NX", "-", "API", "JSON", "request", "to", "the", "NX", "-", "OS", "device", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L181-L199
train
saltstack/salt
salt/utils/nxos.py
NxapiClient.parse_response
def parse_response(self, response, command_list): ''' Parse NX-API JSON response from the NX-OS device. ''' # Check for 500 level NX-API Server Errors if isinstance(response, collections.Iterable) and 'status' in response: if int(response['status']) >= 500: raise NxosError('{}'.format(response)) else: raise NxosError('NX-API Request Not Supported: {}'.format(response)) if isinstance(response, collections.Iterable): body = response['dict'] else: body = response if self.nxargs['connect_over_uds']: body = json.loads(response.read().decode('utf-8')) # Proceed with caution. The JSON may not be complete. # Don't just return body['ins_api']['outputs']['output'] directly. output = body.get('ins_api') if output is None: raise NxosClientError('Unexpected JSON output\n{0}'.format(body)) if output.get('outputs'): output = output['outputs'] if output.get('output'): output = output['output'] # The result list stores results for each command that was sent to # nxapi. result = [] # Keep track of successful commands using previous_commands list so # they can be displayed if a specific command fails in a chain of # commands. previous_commands = [] # Make sure output and command_list lists to be processed in the # subesequent loop. if not isinstance(output, list): output = [output] if isinstance(command_list, string_types): command_list = [cmd.strip() for cmd in command_list.split(';')] if not isinstance(command_list, list): command_list = [command_list] for cmd_result, cmd in zip(output, command_list): code = cmd_result.get('code') msg = cmd_result.get('msg') log.info('command %s:', cmd) log.info('PARSE_RESPONSE: %s %s', code, msg) if code == '400': raise CommandExecutionError({ 'rejected_input': cmd, 'code': code, 'message': msg, 'cli_error': cmd_result.get('clierror'), 'previous_commands': previous_commands, }) elif code == '413': raise NxosRequestNotSupported('Error 413: {}'.format(msg)) elif code != '200': raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code)) else: previous_commands.append(cmd) result.append(cmd_result['body']) return result
python
def parse_response(self, response, command_list): ''' Parse NX-API JSON response from the NX-OS device. ''' # Check for 500 level NX-API Server Errors if isinstance(response, collections.Iterable) and 'status' in response: if int(response['status']) >= 500: raise NxosError('{}'.format(response)) else: raise NxosError('NX-API Request Not Supported: {}'.format(response)) if isinstance(response, collections.Iterable): body = response['dict'] else: body = response if self.nxargs['connect_over_uds']: body = json.loads(response.read().decode('utf-8')) # Proceed with caution. The JSON may not be complete. # Don't just return body['ins_api']['outputs']['output'] directly. output = body.get('ins_api') if output is None: raise NxosClientError('Unexpected JSON output\n{0}'.format(body)) if output.get('outputs'): output = output['outputs'] if output.get('output'): output = output['output'] # The result list stores results for each command that was sent to # nxapi. result = [] # Keep track of successful commands using previous_commands list so # they can be displayed if a specific command fails in a chain of # commands. previous_commands = [] # Make sure output and command_list lists to be processed in the # subesequent loop. if not isinstance(output, list): output = [output] if isinstance(command_list, string_types): command_list = [cmd.strip() for cmd in command_list.split(';')] if not isinstance(command_list, list): command_list = [command_list] for cmd_result, cmd in zip(output, command_list): code = cmd_result.get('code') msg = cmd_result.get('msg') log.info('command %s:', cmd) log.info('PARSE_RESPONSE: %s %s', code, msg) if code == '400': raise CommandExecutionError({ 'rejected_input': cmd, 'code': code, 'message': msg, 'cli_error': cmd_result.get('clierror'), 'previous_commands': previous_commands, }) elif code == '413': raise NxosRequestNotSupported('Error 413: {}'.format(msg)) elif code != '200': raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code)) else: previous_commands.append(cmd) result.append(cmd_result['body']) return result
[ "def", "parse_response", "(", "self", ",", "response", ",", "command_list", ")", ":", "# Check for 500 level NX-API Server Errors", "if", "isinstance", "(", "response", ",", "collections", ".", "Iterable", ")", "and", "'status'", "in", "response", ":", "if", "int"...
Parse NX-API JSON response from the NX-OS device.
[ "Parse", "NX", "-", "API", "JSON", "response", "from", "the", "NX", "-", "OS", "device", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L201-L268
train
saltstack/salt
salt/utils/powershell.py
get_modules
def get_modules(): ''' Get a list of the PowerShell modules which are potentially available to be imported. The intent is to mimic the functionality of ``Get-Module -ListAvailable | Select-Object -Expand Name``, without the delay of loading PowerShell to do so. Returns: list: A list of modules available to Powershell Example: .. code-block:: python import salt.utils.powershell modules = salt.utils.powershell.get_modules() ''' ret = list() valid_extensions = ('.psd1', '.psm1', '.cdxml', '.xaml', '.dll') # need to create an info function to get PS information including version # __salt__ is not available from salt.utils... need to create a salt.util # for the registry to avoid loading powershell to get the version # not sure how to get the powershell version in linux outside of powershell # if running powershell to get version need to use subprocess.Popen # That information will be loaded here # ps_version = info()['version_raw'] root_paths = [] home_dir = os.environ.get('HOME', os.environ.get('HOMEPATH')) system_dir = '{0}\\System32'.format(os.environ.get('WINDIR', 'C:\\Windows')) program_files = os.environ.get('ProgramFiles', 'C:\\Program Files') default_paths = [ '{0}/.local/share/powershell/Modules'.format(home_dir), # Once version is available, these can be enabled # '/opt/microsoft/powershell/{0}/Modules'.format(ps_version), # '/usr/local/microsoft/powershell/{0}/Modules'.format(ps_version), '/usr/local/share/powershell/Modules', '{0}\\WindowsPowerShell\\v1.0\\Modules\\'.format(system_dir), '{0}\\WindowsPowerShell\\Modules'.format(program_files)] default_paths = ';'.join(default_paths) ps_module_path = os.environ.get('PSModulePath', default_paths) # Check if defaults exist, add them if they do ps_module_path = ps_module_path.split(';') for item in ps_module_path: if os.path.exists(item): root_paths.append(item) # Did we find any, if not log the error and return if not root_paths: log.error('Default paths not found') return ret for root_path in root_paths: # only recurse directories if not os.path.isdir(root_path): continue # get a list of all files in the root_path for root_dir, sub_dirs, file_names in salt.utils.path.os_walk(root_path): for file_name in file_names: base_name, file_extension = os.path.splitext(file_name) # If a module file or module manifest is present, check if # the base name matches the directory name. if file_extension.lower() in valid_extensions: dir_name = os.path.basename(os.path.normpath(root_dir)) # Stop recursion once we find a match, and use # the capitalization from the directory name. if dir_name not in ret and \ base_name.lower() == dir_name.lower(): del sub_dirs[:] ret.append(dir_name) return ret
python
def get_modules(): ''' Get a list of the PowerShell modules which are potentially available to be imported. The intent is to mimic the functionality of ``Get-Module -ListAvailable | Select-Object -Expand Name``, without the delay of loading PowerShell to do so. Returns: list: A list of modules available to Powershell Example: .. code-block:: python import salt.utils.powershell modules = salt.utils.powershell.get_modules() ''' ret = list() valid_extensions = ('.psd1', '.psm1', '.cdxml', '.xaml', '.dll') # need to create an info function to get PS information including version # __salt__ is not available from salt.utils... need to create a salt.util # for the registry to avoid loading powershell to get the version # not sure how to get the powershell version in linux outside of powershell # if running powershell to get version need to use subprocess.Popen # That information will be loaded here # ps_version = info()['version_raw'] root_paths = [] home_dir = os.environ.get('HOME', os.environ.get('HOMEPATH')) system_dir = '{0}\\System32'.format(os.environ.get('WINDIR', 'C:\\Windows')) program_files = os.environ.get('ProgramFiles', 'C:\\Program Files') default_paths = [ '{0}/.local/share/powershell/Modules'.format(home_dir), # Once version is available, these can be enabled # '/opt/microsoft/powershell/{0}/Modules'.format(ps_version), # '/usr/local/microsoft/powershell/{0}/Modules'.format(ps_version), '/usr/local/share/powershell/Modules', '{0}\\WindowsPowerShell\\v1.0\\Modules\\'.format(system_dir), '{0}\\WindowsPowerShell\\Modules'.format(program_files)] default_paths = ';'.join(default_paths) ps_module_path = os.environ.get('PSModulePath', default_paths) # Check if defaults exist, add them if they do ps_module_path = ps_module_path.split(';') for item in ps_module_path: if os.path.exists(item): root_paths.append(item) # Did we find any, if not log the error and return if not root_paths: log.error('Default paths not found') return ret for root_path in root_paths: # only recurse directories if not os.path.isdir(root_path): continue # get a list of all files in the root_path for root_dir, sub_dirs, file_names in salt.utils.path.os_walk(root_path): for file_name in file_names: base_name, file_extension = os.path.splitext(file_name) # If a module file or module manifest is present, check if # the base name matches the directory name. if file_extension.lower() in valid_extensions: dir_name = os.path.basename(os.path.normpath(root_dir)) # Stop recursion once we find a match, and use # the capitalization from the directory name. if dir_name not in ret and \ base_name.lower() == dir_name.lower(): del sub_dirs[:] ret.append(dir_name) return ret
[ "def", "get_modules", "(", ")", ":", "ret", "=", "list", "(", ")", "valid_extensions", "=", "(", "'.psd1'", ",", "'.psm1'", ",", "'.cdxml'", ",", "'.xaml'", ",", "'.dll'", ")", "# need to create an info function to get PS information including version", "# __salt__ is...
Get a list of the PowerShell modules which are potentially available to be imported. The intent is to mimic the functionality of ``Get-Module -ListAvailable | Select-Object -Expand Name``, without the delay of loading PowerShell to do so. Returns: list: A list of modules available to Powershell Example: .. code-block:: python import salt.utils.powershell modules = salt.utils.powershell.get_modules()
[ "Get", "a", "list", "of", "the", "PowerShell", "modules", "which", "are", "potentially", "available", "to", "be", "imported", ".", "The", "intent", "is", "to", "mimic", "the", "functionality", "of", "Get", "-", "Module", "-", "ListAvailable", "|", "Select", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/powershell.py#L46-L124
train
saltstack/salt
salt/modules/icinga2.py
generate_cert
def generate_cert(domain): ''' Generate an icinga2 client certificate and key. Returns:: icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt CLI Example: .. code-block:: bash salt '*' icinga2.generate_cert domain.tld ''' result = __salt__['cmd.run_all'](["icinga2", "pki", "new-cert", "--cn", domain, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.crt".format(get_certs_path(), domain)], python_shell=False) return result
python
def generate_cert(domain): ''' Generate an icinga2 client certificate and key. Returns:: icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt CLI Example: .. code-block:: bash salt '*' icinga2.generate_cert domain.tld ''' result = __salt__['cmd.run_all'](["icinga2", "pki", "new-cert", "--cn", domain, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.crt".format(get_certs_path(), domain)], python_shell=False) return result
[ "def", "generate_cert", "(", "domain", ")", ":", "result", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "[", "\"icinga2\"", ",", "\"pki\"", ",", "\"new-cert\"", ",", "\"--cn\"", ",", "domain", ",", "\"--key\"", ",", "\"{0}{1}.key\"", ".", "format", "(", ...
Generate an icinga2 client certificate and key. Returns:: icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt CLI Example: .. code-block:: bash salt '*' icinga2.generate_cert domain.tld
[ "Generate", "an", "icinga2", "client", "certificate", "and", "key", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/icinga2.py#L53-L68
train
saltstack/salt
salt/modules/icinga2.py
save_cert
def save_cert(domain, master): ''' Save the certificate for master icinga2 node. Returns:: icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld CLI Example: .. code-block:: bash salt '*' icinga2.save_cert domain.tld master.domain.tld ''' result = __salt__['cmd.run_all'](["icinga2", "pki", "save-cert", "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.cert".format(get_certs_path(), domain), "--trustedcert", "{0}trusted-master.crt".format(get_certs_path()), "--host", master], python_shell=False) return result
python
def save_cert(domain, master): ''' Save the certificate for master icinga2 node. Returns:: icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld CLI Example: .. code-block:: bash salt '*' icinga2.save_cert domain.tld master.domain.tld ''' result = __salt__['cmd.run_all'](["icinga2", "pki", "save-cert", "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.cert".format(get_certs_path(), domain), "--trustedcert", "{0}trusted-master.crt".format(get_certs_path()), "--host", master], python_shell=False) return result
[ "def", "save_cert", "(", "domain", ",", "master", ")", ":", "result", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "[", "\"icinga2\"", ",", "\"pki\"", ",", "\"save-cert\"", ",", "\"--key\"", ",", "\"{0}{1}.key\"", ".", "format", "(", "get_certs_path", "(...
Save the certificate for master icinga2 node. Returns:: icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld CLI Example: .. code-block:: bash salt '*' icinga2.save_cert domain.tld master.domain.tld
[ "Save", "the", "certificate", "for", "master", "icinga2", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/icinga2.py#L71-L87
train
saltstack/salt
salt/modules/icinga2.py
request_cert
def request_cert(domain, master, ticket, port): ''' Request CA cert from master icinga2 node. Returns:: icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \ /etc/icinga2/pki/trusted-master.crt --ca /etc/icinga2/pki/ca.crt CLI Example: .. code-block:: bash salt '*' icinga2.request_cert domain.tld master.domain.tld TICKET_ID ''' result = __salt__['cmd.run_all'](["icinga2", "pki", "request", "--host", master, "--port", port, "--ticket", ticket, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.crt".format(get_certs_path(), domain), "--trustedcert", "{0}trusted-master.crt".format(get_certs_path()), "--ca", "{0}ca.crt".format(get_certs_path())], python_shell=False) return result
python
def request_cert(domain, master, ticket, port): ''' Request CA cert from master icinga2 node. Returns:: icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \ /etc/icinga2/pki/trusted-master.crt --ca /etc/icinga2/pki/ca.crt CLI Example: .. code-block:: bash salt '*' icinga2.request_cert domain.tld master.domain.tld TICKET_ID ''' result = __salt__['cmd.run_all'](["icinga2", "pki", "request", "--host", master, "--port", port, "--ticket", ticket, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.crt".format(get_certs_path(), domain), "--trustedcert", "{0}trusted-master.crt".format(get_certs_path()), "--ca", "{0}ca.crt".format(get_certs_path())], python_shell=False) return result
[ "def", "request_cert", "(", "domain", ",", "master", ",", "ticket", ",", "port", ")", ":", "result", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "[", "\"icinga2\"", ",", "\"pki\"", ",", "\"request\"", ",", "\"--host\"", ",", "master", ",", "\"--port\"...
Request CA cert from master icinga2 node. Returns:: icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \ /etc/icinga2/pki/trusted-master.crt --ca /etc/icinga2/pki/ca.crt CLI Example: .. code-block:: bash salt '*' icinga2.request_cert domain.tld master.domain.tld TICKET_ID
[ "Request", "CA", "cert", "from", "master", "icinga2", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/icinga2.py#L90-L107
train
saltstack/salt
salt/modules/icinga2.py
node_setup
def node_setup(domain, master, ticket): ''' Setup the icinga2 node. Returns:: icinga2 node setup --ticket TICKET_ID --endpoint master.domain.tld --zone domain.tld --master_host master.domain.tld --trustedcert \ /etc/icinga2/pki/trusted-master.crt CLI Example: .. code-block:: bash salt '*' icinga2.node_setup domain.tld master.domain.tld TICKET_ID ''' result = __salt__['cmd.run_all'](["icinga2", "node", "setup", "--ticket", ticket, "--endpoint", master, "--zone", domain, "--master_host", master, "--trustedcert", "{0}trusted-master.crt".format(get_certs_path())], python_shell=False) return result
python
def node_setup(domain, master, ticket): ''' Setup the icinga2 node. Returns:: icinga2 node setup --ticket TICKET_ID --endpoint master.domain.tld --zone domain.tld --master_host master.domain.tld --trustedcert \ /etc/icinga2/pki/trusted-master.crt CLI Example: .. code-block:: bash salt '*' icinga2.node_setup domain.tld master.domain.tld TICKET_ID ''' result = __salt__['cmd.run_all'](["icinga2", "node", "setup", "--ticket", ticket, "--endpoint", master, "--zone", domain, "--master_host", master, "--trustedcert", "{0}trusted-master.crt".format(get_certs_path())], python_shell=False) return result
[ "def", "node_setup", "(", "domain", ",", "master", ",", "ticket", ")", ":", "result", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "[", "\"icinga2\"", ",", "\"node\"", ",", "\"setup\"", ",", "\"--ticket\"", ",", "ticket", ",", "\"--endpoint\"", ",", "m...
Setup the icinga2 node. Returns:: icinga2 node setup --ticket TICKET_ID --endpoint master.domain.tld --zone domain.tld --master_host master.domain.tld --trustedcert \ /etc/icinga2/pki/trusted-master.crt CLI Example: .. code-block:: bash salt '*' icinga2.node_setup domain.tld master.domain.tld TICKET_ID
[ "Setup", "the", "icinga2", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/icinga2.py#L110-L127
train
saltstack/salt
salt/roster/terraform.py
_handle_salt_host_resource
def _handle_salt_host_resource(resource): ''' Handles salt_host resources. See https://github.com/dmacvicar/terraform-provider-salt Returns roster attributes for the resource or None ''' ret = {} attrs = resource.get('primary', {}).get('attributes', {}) ret[MINION_ID] = attrs.get(MINION_ID) valid_attrs = set(attrs.keys()).intersection(TF_ROSTER_ATTRS.keys()) for attr in valid_attrs: ret[attr] = _cast_output_to_type(attrs.get(attr), TF_ROSTER_ATTRS.get(attr)) return ret
python
def _handle_salt_host_resource(resource): ''' Handles salt_host resources. See https://github.com/dmacvicar/terraform-provider-salt Returns roster attributes for the resource or None ''' ret = {} attrs = resource.get('primary', {}).get('attributes', {}) ret[MINION_ID] = attrs.get(MINION_ID) valid_attrs = set(attrs.keys()).intersection(TF_ROSTER_ATTRS.keys()) for attr in valid_attrs: ret[attr] = _cast_output_to_type(attrs.get(attr), TF_ROSTER_ATTRS.get(attr)) return ret
[ "def", "_handle_salt_host_resource", "(", "resource", ")", ":", "ret", "=", "{", "}", "attrs", "=", "resource", ".", "get", "(", "'primary'", ",", "{", "}", ")", ".", "get", "(", "'attributes'", ",", "{", "}", ")", "ret", "[", "MINION_ID", "]", "=", ...
Handles salt_host resources. See https://github.com/dmacvicar/terraform-provider-salt Returns roster attributes for the resource or None
[ "Handles", "salt_host", "resources", ".", "See", "https", ":", "//", "github", ".", "com", "/", "dmacvicar", "/", "terraform", "-", "provider", "-", "salt" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L83-L96
train
saltstack/salt
salt/roster/terraform.py
_add_ssh_key
def _add_ssh_key(ret): ''' Setups the salt-ssh minion to be accessed with salt-ssh default key ''' priv = None if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')): priv = os.path.expanduser('~/.ssh/id_rsa') else: priv = __opts__.get( 'ssh_priv', os.path.abspath(os.path.join( __opts__['pki_dir'], 'ssh', 'salt-ssh.rsa' )) ) if priv and os.path.isfile(priv): ret['priv'] = priv
python
def _add_ssh_key(ret): ''' Setups the salt-ssh minion to be accessed with salt-ssh default key ''' priv = None if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')): priv = os.path.expanduser('~/.ssh/id_rsa') else: priv = __opts__.get( 'ssh_priv', os.path.abspath(os.path.join( __opts__['pki_dir'], 'ssh', 'salt-ssh.rsa' )) ) if priv and os.path.isfile(priv): ret['priv'] = priv
[ "def", "_add_ssh_key", "(", "ret", ")", ":", "priv", "=", "None", "if", "__opts__", ".", "get", "(", "'ssh_use_home_key'", ")", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "expanduser", "(", "'~/.ssh/id_rsa'", ")", ")", ":", ...
Setups the salt-ssh minion to be accessed with salt-ssh default key
[ "Setups", "the", "salt", "-", "ssh", "minion", "to", "be", "accessed", "with", "salt", "-", "ssh", "default", "key" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L99-L116
train
saltstack/salt
salt/roster/terraform.py
_cast_output_to_type
def _cast_output_to_type(value, typ): '''cast the value depending on the terraform type''' if typ == 'b': return bool(value) if typ == 'i': return int(value) return value
python
def _cast_output_to_type(value, typ): '''cast the value depending on the terraform type''' if typ == 'b': return bool(value) if typ == 'i': return int(value) return value
[ "def", "_cast_output_to_type", "(", "value", ",", "typ", ")", ":", "if", "typ", "==", "'b'", ":", "return", "bool", "(", "value", ")", "if", "typ", "==", "'i'", ":", "return", "int", "(", "value", ")", "return", "value" ]
cast the value depending on the terraform type
[ "cast", "the", "value", "depending", "on", "the", "terraform", "type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L119-L125
train
saltstack/salt
salt/roster/terraform.py
_parse_state_file
def _parse_state_file(state_file_path='terraform.tfstate'): ''' Parses the terraform state file passing different resource types to the right handler ''' ret = {} with salt.utils.files.fopen(state_file_path, 'r') as fh_: tfstate = salt.utils.json.load(fh_) modules = tfstate.get('modules') if not modules: log.error('Malformed tfstate file. No modules found') return ret for module in modules: resources = module.get('resources', []) for resource_name, resource in salt.ext.six.iteritems(resources): roster_entry = None if resource['type'] == 'salt_host': roster_entry = _handle_salt_host_resource(resource) if not roster_entry: continue minion_id = roster_entry.get(MINION_ID, resource.get('id')) if not minion_id: continue if MINION_ID in roster_entry: del roster_entry[MINION_ID] _add_ssh_key(roster_entry) ret[minion_id] = roster_entry return ret
python
def _parse_state_file(state_file_path='terraform.tfstate'): ''' Parses the terraform state file passing different resource types to the right handler ''' ret = {} with salt.utils.files.fopen(state_file_path, 'r') as fh_: tfstate = salt.utils.json.load(fh_) modules = tfstate.get('modules') if not modules: log.error('Malformed tfstate file. No modules found') return ret for module in modules: resources = module.get('resources', []) for resource_name, resource in salt.ext.six.iteritems(resources): roster_entry = None if resource['type'] == 'salt_host': roster_entry = _handle_salt_host_resource(resource) if not roster_entry: continue minion_id = roster_entry.get(MINION_ID, resource.get('id')) if not minion_id: continue if MINION_ID in roster_entry: del roster_entry[MINION_ID] _add_ssh_key(roster_entry) ret[minion_id] = roster_entry return ret
[ "def", "_parse_state_file", "(", "state_file_path", "=", "'terraform.tfstate'", ")", ":", "ret", "=", "{", "}", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "state_file_path", ",", "'r'", ")", "as", "fh_", ":", "tfstate", "=", "salt", "...
Parses the terraform state file passing different resource types to the right handler
[ "Parses", "the", "terraform", "state", "file", "passing", "different", "resource", "types", "to", "the", "right", "handler" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L128-L159
train
saltstack/salt
salt/roster/terraform.py
targets
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613 ''' Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate ''' roster_file = os.path.abspath('terraform.tfstate') if __opts__.get('roster_file'): roster_file = os.path.abspath(__opts__['roster_file']) if not os.path.isfile(roster_file): log.error("Can't find terraform state file '%s'", roster_file) return {} log.debug('terraform roster: using %s state file', roster_file) if not roster_file.endswith('.tfstate'): log.error("Terraform roster can only be used with terraform state files") return {} raw = _parse_state_file(roster_file) log.debug('%s hosts in terraform state file', len(raw)) return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
python
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613 ''' Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate ''' roster_file = os.path.abspath('terraform.tfstate') if __opts__.get('roster_file'): roster_file = os.path.abspath(__opts__['roster_file']) if not os.path.isfile(roster_file): log.error("Can't find terraform state file '%s'", roster_file) return {} log.debug('terraform roster: using %s state file', roster_file) if not roster_file.endswith('.tfstate'): log.error("Terraform roster can only be used with terraform state files") return {} raw = _parse_state_file(roster_file) log.debug('%s hosts in terraform state file', len(raw)) return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
[ "def", "targets", "(", "tgt", ",", "tgt_type", "=", "'glob'", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "roster_file", "=", "os", ".", "path", ".", "abspath", "(", "'terraform.tfstate'", ")", "if", "__opts__", ".", "get", "(", "'roster_...
Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate
[ "Returns", "the", "roster", "from", "the", "terraform", "state", "file", "checks", "opts", "for", "location", "but", "defaults", "to", "terraform", ".", "tfstate" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L162-L182
train
saltstack/salt
salt/states/win_powercfg.py
set_timeout
def set_timeout(name, value, power='ac', scheme=None): ''' Set the sleep timeouts of specific items such as disk, monitor, etc. Args: name (str) The setting to change, can be one of the following: - ``monitor`` - ``disk`` - ``standby`` - ``hibernate`` value (int): The amount of time in minutes before the item will timeout power (str): Set the value for AC or DC power. Default is ``ac``. Valid options are: - ``ac`` (AC Power) - ``dc`` (Battery) scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance CLI Example: .. code-block:: yaml # Set monitor timeout to 30 minutes on Battery monitor: powercfg.set_timeout: - value: 30 - power: dc # Set disk timeout to 10 minutes on AC Power disk: powercfg.set_timeout: - value: 10 - power: ac ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} # Validate name values name = name.lower() if name not in ['monitor', 'disk', 'standby', 'hibernate']: ret['result'] = False ret['comment'] = '"{0}" is not a valid setting'.format(name) log.debug(ret['comment']) return ret # Validate power values power = power.lower() if power not in ['ac', 'dc']: ret['result'] = False ret['comment'] = '"{0}" is not a power type'.format(power) log.debug(ret['comment']) return ret # Get current settings old = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme) # Check current settings if old[power] == value: ret['comment'] = '{0} timeout on {1} power is already set to {2}' \ ''.format(name.capitalize(), power.upper(), value) return ret else: ret['comment'] = '{0} timeout on {1} power will be set to {2}' \ ''.format(name.capitalize(), power.upper(), value) # Check for test=True if __opts__['test']: ret['result'] = None return ret # Set the timeout value __salt__['powercfg.set_{0}_timeout'.format(name)]( timeout=value, power=power, scheme=scheme) # Get the setting after the change new = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme) changes = salt.utils.data.compare_dicts(old, new) if changes: ret['changes'] = {name: changes} ret['comment'] = '{0} timeout on {1} power set to {2}' \ ''.format(name.capitalize(), power.upper(), value) log.debug(ret['comment']) else: ret['changes'] = {} ret['comment'] = 'Failed to set {0} timeout on {1} power to {2}' \ ''.format(name, power.upper(), value) log.debug(ret['comment']) ret['result'] = False return ret
python
def set_timeout(name, value, power='ac', scheme=None): ''' Set the sleep timeouts of specific items such as disk, monitor, etc. Args: name (str) The setting to change, can be one of the following: - ``monitor`` - ``disk`` - ``standby`` - ``hibernate`` value (int): The amount of time in minutes before the item will timeout power (str): Set the value for AC or DC power. Default is ``ac``. Valid options are: - ``ac`` (AC Power) - ``dc`` (Battery) scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance CLI Example: .. code-block:: yaml # Set monitor timeout to 30 minutes on Battery monitor: powercfg.set_timeout: - value: 30 - power: dc # Set disk timeout to 10 minutes on AC Power disk: powercfg.set_timeout: - value: 10 - power: ac ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} # Validate name values name = name.lower() if name not in ['monitor', 'disk', 'standby', 'hibernate']: ret['result'] = False ret['comment'] = '"{0}" is not a valid setting'.format(name) log.debug(ret['comment']) return ret # Validate power values power = power.lower() if power not in ['ac', 'dc']: ret['result'] = False ret['comment'] = '"{0}" is not a power type'.format(power) log.debug(ret['comment']) return ret # Get current settings old = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme) # Check current settings if old[power] == value: ret['comment'] = '{0} timeout on {1} power is already set to {2}' \ ''.format(name.capitalize(), power.upper(), value) return ret else: ret['comment'] = '{0} timeout on {1} power will be set to {2}' \ ''.format(name.capitalize(), power.upper(), value) # Check for test=True if __opts__['test']: ret['result'] = None return ret # Set the timeout value __salt__['powercfg.set_{0}_timeout'.format(name)]( timeout=value, power=power, scheme=scheme) # Get the setting after the change new = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme) changes = salt.utils.data.compare_dicts(old, new) if changes: ret['changes'] = {name: changes} ret['comment'] = '{0} timeout on {1} power set to {2}' \ ''.format(name.capitalize(), power.upper(), value) log.debug(ret['comment']) else: ret['changes'] = {} ret['comment'] = 'Failed to set {0} timeout on {1} power to {2}' \ ''.format(name, power.upper(), value) log.debug(ret['comment']) ret['result'] = False return ret
[ "def", "set_timeout", "(", "name", ",", "value", ",", "power", "=", "'ac'", ",", "scheme", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", ...
Set the sleep timeouts of specific items such as disk, monitor, etc. Args: name (str) The setting to change, can be one of the following: - ``monitor`` - ``disk`` - ``standby`` - ``hibernate`` value (int): The amount of time in minutes before the item will timeout power (str): Set the value for AC or DC power. Default is ``ac``. Valid options are: - ``ac`` (AC Power) - ``dc`` (Battery) scheme (str): The scheme to use, leave as ``None`` to use the current. Default is ``None``. This can be the GUID or the Alias for the Scheme. Known Aliases are: - ``SCHEME_BALANCED`` - Balanced - ``SCHEME_MAX`` - Power saver - ``SCHEME_MIN`` - High performance CLI Example: .. code-block:: yaml # Set monitor timeout to 30 minutes on Battery monitor: powercfg.set_timeout: - value: 30 - power: dc # Set disk timeout to 10 minutes on AC Power disk: powercfg.set_timeout: - value: 10 - power: ac
[ "Set", "the", "sleep", "timeouts", "of", "specific", "items", "such", "as", "disk", "monitor", "etc", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_powercfg.py#L40-L150
train
saltstack/salt
salt/minion.py
resolve_dns
def resolve_dns(opts, fallback=True): ''' Resolves the master_ip and master_uri options ''' ret = {} check_dns = True if (opts.get('file_client', 'remote') == 'local' and not opts.get('use_master_when_local', False)): check_dns = False # Since salt.log is imported below, salt.utils.network needs to be imported here as well import salt.utils.network if check_dns is True: try: if opts['master'] == '': raise SaltSystemExit ret['master_ip'] = salt.utils.network.dns_check( opts['master'], int(opts['master_port']), True, opts['ipv6'], attempt_connect=False) except SaltClientError: retry_dns_count = opts.get('retry_dns_count', None) if opts['retry_dns']: while True: if retry_dns_count is not None: if retry_dns_count == 0: raise SaltMasterUnresolvableError retry_dns_count -= 1 import salt.log msg = ('Master hostname: \'{0}\' not found or not responsive. ' 'Retrying in {1} seconds').format(opts['master'], opts['retry_dns']) if salt.log.setup.is_console_configured(): log.error(msg) else: print('WARNING: {0}'.format(msg)) time.sleep(opts['retry_dns']) try: ret['master_ip'] = salt.utils.network.dns_check( opts['master'], int(opts['master_port']), True, opts['ipv6'], attempt_connect=False) break except SaltClientError: pass else: if fallback: ret['master_ip'] = '127.0.0.1' else: raise except SaltSystemExit: unknown_str = 'unknown address' master = opts.get('master', unknown_str) if master == '': master = unknown_str if opts.get('__role') == 'syndic': err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \ 'Set \'syndic_master\' value in minion config.'.format(master) else: err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \ 'Set \'master\' value in minion config.'.format(master) log.error(err) raise SaltSystemExit(code=42, msg=err) else: ret['master_ip'] = '127.0.0.1' if 'master_ip' in ret and 'master_ip' in opts: if ret['master_ip'] != opts['master_ip']: log.warning( 'Master ip address changed from %s to %s', opts['master_ip'], ret['master_ip'] ) if opts['source_interface_name']: log.trace('Custom source interface required: %s', opts['source_interface_name']) interfaces = salt.utils.network.interfaces() log.trace('The following interfaces are available on this Minion:') log.trace(interfaces) if opts['source_interface_name'] in interfaces: if interfaces[opts['source_interface_name']]['up']: addrs = interfaces[opts['source_interface_name']]['inet'] if not opts['ipv6'] else\ interfaces[opts['source_interface_name']]['inet6'] ret['source_ip'] = addrs[0]['address'] log.debug('Using %s as source IP address', ret['source_ip']) else: log.warning('The interface %s is down so it cannot be used as source to connect to the Master', opts['source_interface_name']) else: log.warning('%s is not a valid interface. Ignoring.', opts['source_interface_name']) elif opts['source_address']: ret['source_ip'] = salt.utils.network.dns_check( opts['source_address'], int(opts['source_ret_port']), True, opts['ipv6'], attempt_connect=False) log.debug('Using %s as source IP address', ret['source_ip']) if opts['source_ret_port']: ret['source_ret_port'] = int(opts['source_ret_port']) log.debug('Using %d as source port for the ret server', ret['source_ret_port']) if opts['source_publish_port']: ret['source_publish_port'] = int(opts['source_publish_port']) log.debug('Using %d as source port for the master pub', ret['source_publish_port']) ret['master_uri'] = 'tcp://{ip}:{port}'.format( ip=ret['master_ip'], port=opts['master_port']) log.debug('Master URI: %s', ret['master_uri']) return ret
python
def resolve_dns(opts, fallback=True): ''' Resolves the master_ip and master_uri options ''' ret = {} check_dns = True if (opts.get('file_client', 'remote') == 'local' and not opts.get('use_master_when_local', False)): check_dns = False # Since salt.log is imported below, salt.utils.network needs to be imported here as well import salt.utils.network if check_dns is True: try: if opts['master'] == '': raise SaltSystemExit ret['master_ip'] = salt.utils.network.dns_check( opts['master'], int(opts['master_port']), True, opts['ipv6'], attempt_connect=False) except SaltClientError: retry_dns_count = opts.get('retry_dns_count', None) if opts['retry_dns']: while True: if retry_dns_count is not None: if retry_dns_count == 0: raise SaltMasterUnresolvableError retry_dns_count -= 1 import salt.log msg = ('Master hostname: \'{0}\' not found or not responsive. ' 'Retrying in {1} seconds').format(opts['master'], opts['retry_dns']) if salt.log.setup.is_console_configured(): log.error(msg) else: print('WARNING: {0}'.format(msg)) time.sleep(opts['retry_dns']) try: ret['master_ip'] = salt.utils.network.dns_check( opts['master'], int(opts['master_port']), True, opts['ipv6'], attempt_connect=False) break except SaltClientError: pass else: if fallback: ret['master_ip'] = '127.0.0.1' else: raise except SaltSystemExit: unknown_str = 'unknown address' master = opts.get('master', unknown_str) if master == '': master = unknown_str if opts.get('__role') == 'syndic': err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \ 'Set \'syndic_master\' value in minion config.'.format(master) else: err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \ 'Set \'master\' value in minion config.'.format(master) log.error(err) raise SaltSystemExit(code=42, msg=err) else: ret['master_ip'] = '127.0.0.1' if 'master_ip' in ret and 'master_ip' in opts: if ret['master_ip'] != opts['master_ip']: log.warning( 'Master ip address changed from %s to %s', opts['master_ip'], ret['master_ip'] ) if opts['source_interface_name']: log.trace('Custom source interface required: %s', opts['source_interface_name']) interfaces = salt.utils.network.interfaces() log.trace('The following interfaces are available on this Minion:') log.trace(interfaces) if opts['source_interface_name'] in interfaces: if interfaces[opts['source_interface_name']]['up']: addrs = interfaces[opts['source_interface_name']]['inet'] if not opts['ipv6'] else\ interfaces[opts['source_interface_name']]['inet6'] ret['source_ip'] = addrs[0]['address'] log.debug('Using %s as source IP address', ret['source_ip']) else: log.warning('The interface %s is down so it cannot be used as source to connect to the Master', opts['source_interface_name']) else: log.warning('%s is not a valid interface. Ignoring.', opts['source_interface_name']) elif opts['source_address']: ret['source_ip'] = salt.utils.network.dns_check( opts['source_address'], int(opts['source_ret_port']), True, opts['ipv6'], attempt_connect=False) log.debug('Using %s as source IP address', ret['source_ip']) if opts['source_ret_port']: ret['source_ret_port'] = int(opts['source_ret_port']) log.debug('Using %d as source port for the ret server', ret['source_ret_port']) if opts['source_publish_port']: ret['source_publish_port'] = int(opts['source_publish_port']) log.debug('Using %d as source port for the master pub', ret['source_publish_port']) ret['master_uri'] = 'tcp://{ip}:{port}'.format( ip=ret['master_ip'], port=opts['master_port']) log.debug('Master URI: %s', ret['master_uri']) return ret
[ "def", "resolve_dns", "(", "opts", ",", "fallback", "=", "True", ")", ":", "ret", "=", "{", "}", "check_dns", "=", "True", "if", "(", "opts", ".", "get", "(", "'file_client'", ",", "'remote'", ")", "==", "'local'", "and", "not", "opts", ".", "get", ...
Resolves the master_ip and master_uri options
[ "Resolves", "the", "master_ip", "and", "master_uri", "options" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/minion.py#L133-L242
train
saltstack/salt
salt/minion.py
prep_ip_port
def prep_ip_port(opts): ''' parse host:port values from opts['master'] and return valid: master: ip address or hostname as a string master_port: (optional) master returner port as integer e.g.: - master: 'localhost:1234' -> {'master': 'localhost', 'master_port': 1234} - master: '127.0.0.1:1234' -> {'master': '127.0.0.1', 'master_port' :1234} - master: '[::1]:1234' -> {'master': '::1', 'master_port': 1234} - master: 'fe80::a00:27ff:fedc:ba98' -> {'master': 'fe80::a00:27ff:fedc:ba98'} ''' ret = {} # Use given master IP if "ip_only" is set or if master_ip is an ipv6 address without # a port specified. The is_ipv6 check returns False if brackets are used in the IP # definition such as master: '[::1]:1234'. if opts['master_uri_format'] == 'ip_only': ret['master'] = ipaddress.ip_address(opts['master']) else: host, port = parse_host_port(opts['master']) ret = {'master': host} if port: ret.update({'master_port': port}) return ret
python
def prep_ip_port(opts): ''' parse host:port values from opts['master'] and return valid: master: ip address or hostname as a string master_port: (optional) master returner port as integer e.g.: - master: 'localhost:1234' -> {'master': 'localhost', 'master_port': 1234} - master: '127.0.0.1:1234' -> {'master': '127.0.0.1', 'master_port' :1234} - master: '[::1]:1234' -> {'master': '::1', 'master_port': 1234} - master: 'fe80::a00:27ff:fedc:ba98' -> {'master': 'fe80::a00:27ff:fedc:ba98'} ''' ret = {} # Use given master IP if "ip_only" is set or if master_ip is an ipv6 address without # a port specified. The is_ipv6 check returns False if brackets are used in the IP # definition such as master: '[::1]:1234'. if opts['master_uri_format'] == 'ip_only': ret['master'] = ipaddress.ip_address(opts['master']) else: host, port = parse_host_port(opts['master']) ret = {'master': host} if port: ret.update({'master_port': port}) return ret
[ "def", "prep_ip_port", "(", "opts", ")", ":", "ret", "=", "{", "}", "# Use given master IP if \"ip_only\" is set or if master_ip is an ipv6 address without", "# a port specified. The is_ipv6 check returns False if brackets are used in the IP", "# definition such as master: '[::1]:1234'.", ...
parse host:port values from opts['master'] and return valid: master: ip address or hostname as a string master_port: (optional) master returner port as integer e.g.: - master: 'localhost:1234' -> {'master': 'localhost', 'master_port': 1234} - master: '127.0.0.1:1234' -> {'master': '127.0.0.1', 'master_port' :1234} - master: '[::1]:1234' -> {'master': '::1', 'master_port': 1234} - master: 'fe80::a00:27ff:fedc:ba98' -> {'master': 'fe80::a00:27ff:fedc:ba98'}
[ "parse", "host", ":", "port", "values", "from", "opts", "[", "master", "]", "and", "return", "valid", ":", "master", ":", "ip", "address", "or", "hostname", "as", "a", "string", "master_port", ":", "(", "optional", ")", "master", "returner", "port", "as"...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/minion.py#L245-L269
train