desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry.'
@property def is_global(self):
return ((not ((self.network_address in IPv4Network('100.64.0.0/10')) and (self.broadcast_address in IPv4Network('100.64.0.0/10')))) and (not self.is_private))
'Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn\'t a valid IPv6 Address.'
def _ip_int_from_string(self, ip_str):
if (not ip_str): raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') _min_parts = 3 if (len(parts) < _min_parts): msg = ('At least %d parts expected in %r' % (_min_parts, ip_str)) raise AddressValueError(msg) if ('.' in part...
'Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn\'t strictly a hex number from [0..FFFF].'
def _parse_hextet(self, hextet_str):
if (not self._HEX_DIGITS.issuperset(hextet_str)): raise ValueError(('Only hex digits permitted in %r' % hextet_str)) if (len(hextet_str) > 4): msg = 'At most 4 characters permitted in %r' raise ValueError((msg % hextet_str)) return int(hextet_str, 16)...
'Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets:...
def _compress_hextets(self, hextets):
best_doublecolon_start = (-1) best_doublecolon_len = 0 doublecolon_start = (-1) doublecolon_len = 0 for (index, hextet) in enumerate(hextets): if (hextet == '0'): doublecolon_len += 1 if (doublecolon_start == (-1)): doublecolon_start = index ...
'Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones.'
def _string_from_ip_int(self, ip_int=None):
if (ip_int is None): ip_int = int(self._ip) if (ip_int > self._ALL_ONES): raise ValueError('IPv6 address is too large') hex_str = ('%032x' % ip_int) hextets = [('%x' % int(hex_str[x:(x + 4)], 16)) for x in range(0, 32, 4)] hextets = self._compress_hextets(hextets) ret...
'Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address.'
def _explode_shorthand_ip_string(self):
if isinstance(self, IPv6Network): ip_str = str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = ('%032x' % ip_int) parts = [hex_str[x:(x + 4)] for x in range(0, 3...
'Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5.'
def _reverse_pointer(self):
reverse_chars = self.exploded[::(-1)].replace(':', '') return ('.'.join(reverse_chars) + '.ip6.arpa')
'Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address(\'2001:db8::\') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address(\'2001:db8::\'))) == IPv6Address(\'2001:db8::\') Rai...
def __init__(self, address):
_BaseAddress.__init__(self, address) _BaseV6.__init__(self, address) if isinstance(address, int): self._check_int_address(address) self._ip = address return if isinstance(address, bytes): self._check_packed_address(address, 16) self._ip = _int_from_bytes(address, ...
'The binary representation of this address.'
@property def packed(self):
return v6_int_to_packed(self._ip)
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details.'
@property def is_multicast(self):
multicast_network = IPv6Network('ff00::/8') return (self in multicast_network)
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges.'
@property def is_reserved(self):
reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'), IPv6Network('200::/7'), IPv6Network('400::/6'), IPv6Network('800::/5'), IPv6Network('1000::/4'), IPv6Network('4000::/3'), IPv6Network('6000::/3'), IPv6Network('8000::/3'), IPv6Network('A000::/3'), IPv6Network('C000::/3'), IPv6Network('E000::/4'), IPv...
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291.'
@property def is_link_local(self):
linklocal_network = IPv6Network('fe80::/10') return (self in linklocal_network)
'Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6.'
@property def is_site_local(self):
sitelocal_network = IPv6Network('fec0::/10') return (self in sitelocal_network)
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry.'
@property def is_private(self):
return ((self in IPv6Network('::1/128')) or (self in IPv6Network('::/128')) or (self in IPv6Network('::ffff:0:0/96')) or (self in IPv6Network('100::/64')) or (self in IPv6Network('2001::/23')) or (self in IPv6Network('2001:2::/48')) or (self in IPv6Network('2001:db8::/32')) or (self in IPv6Network('2001:10::/28')) ...
'Test if this address is allocated for public networks. Returns: A boolean, true if the address is not reserved per iana-ipv6-special-registry.'
@property def is_global(self):
return (not self.is_private)
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2.'
@property def is_unspecified(self):
return (self._ip == 0)
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3.'
@property def is_loopback(self):
return (self._ip == 1)
'Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise.'
@property def ipv4_mapped(self):
if ((self._ip >> 32) != 65535): return None return IPv4Address((self._ip & 4294967295))
'Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn\'t appear to be a teredo address (doesn\'t start with 2001::/32)'
@property def teredo(self):
if ((self._ip >> 96) != 536936448): return None return (IPv4Address(((self._ip >> 64) & 4294967295)), IPv4Address(((~ self._ip) & 4294967295)))
'Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn\'t appear to contain a 6to4 embedded address.'
@property def sixtofour(self):
if ((self._ip >> 112) != 8194): return None return IPv4Address(((self._ip >> 80) & 4294967295))
'Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. \'2001:db8::/128\' \'2001:db8:0000:0000:0000:0000:0000:0000/128\' \'2001:db8::\' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an o...
def __init__(self, address, strict=True):
_BaseV6.__init__(self, address) _BaseNetwork.__init__(self, address) if isinstance(address, int): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return if isinstance(address, bytes): sel...
'Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn\'t return the Subnet-Router anycast address.'
def hosts(self):
network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range(1, ((broadcast - network) + 1)): (yield self._address_class((network + x)))
'Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6.'
@property def is_site_local(self):
return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
'Return the backend list'
def _gen_back(self, back):
if (not back): back = self.opts['fileserver_backend'] elif (not isinstance(back, list)): try: back = back.split(',') except AttributeError: back = six.text_type(back).split(',') if isinstance(back, collections.Sequence): back = list(back) ret = [] ...
'Simplify master opts'
def master_opts(self, load):
return self.opts
'Clear the cache of all of the fileserver backends that support the clear_cache function or the named backend(s) only.'
def clear_cache(self, back=None):
back = self._gen_back(back) cleared = [] errors = [] for fsb in back: fstr = '{0}.clear_cache'.format(fsb) if (fstr in self.servers): log.debug('Clearing {0} fileserver cache'.format(fsb)) failed = self.servers[fstr]() if failed: ...
'``remote`` can either be a dictionary containing repo configuration information, or a pattern. If the latter, then remotes for which the URL matches the pattern will be locked.'
def lock(self, back=None, remote=None):
back = self._gen_back(back) locked = [] errors = [] for fsb in back: fstr = '{0}.lock'.format(fsb) if (fstr in self.servers): msg = 'Setting update lock for {0} remotes'.format(fsb) if remote: if (not isinstance(remote, six.string_ty...
'Clear the update lock for the enabled fileserver backends back Only clear the update lock for the specified backend(s). The default is to clear the lock for all enabled backends remote If specified, then any remotes which contain the passed string will have their lock cleared.'
def clear_lock(self, back=None, remote=None):
back = self._gen_back(back) cleared = [] errors = [] for fsb in back: fstr = '{0}.clear_lock'.format(fsb) if (fstr in self.servers): (good, bad) = clear_lock(self.servers[fstr], fsb, remote=remote) cleared.extend(good) errors.extend(bad) return (cl...
'Update all of the enabled fileserver backends which support the update function, or'
def update(self, back=None):
back = self._gen_back(back) for fsb in back: fstr = '{0}.update'.format(fsb) if (fstr in self.servers): log.debug('Updating {0} fileserver cache'.format(fsb)) self.servers[fstr]()
'Return the environments for the named backend or all backends'
def envs(self, back=None, sources=False):
back = self._gen_back(back) ret = set() if sources: ret = {} for fsb in back: fstr = '{0}.envs'.format(fsb) kwargs = ({'ignore_cache': True} if (('ignore_cache' in _argspec(self.servers[fstr]).args) and (self.opts['__role'] == 'minion')) else {}) if sources: r...
'Initialize the backend, only do so if the fs supports an init function'
def init(self, back=None):
back = self._gen_back(back) for fsb in back: fstr = '{0}.init'.format(fsb) if (fstr in self.servers): self.servers[fstr]()
'Convenience function for calls made using the RemoteClient'
def _find_file(self, load):
path = load.get('path') if (not path): return {'path': '', 'rel': ''} tgt_env = load.get('saltenv', 'base') return self.find_file(path, tgt_env)
'Convenience function for calls made using the LocalClient'
def file_find(self, load):
path = load.get('path') if (not path): return {'path': '', 'rel': ''} tgt_env = load.get('saltenv', 'base') return self.find_file(path, tgt_env)
'Find the path and return the fnd structure, this structure is passed to other backend interfaces.'
def find_file(self, path, saltenv, back=None):
back = self._gen_back(back) kwargs = {} fnd = {'path': '', 'rel': ''} if os.path.isabs(path): return fnd if ('../' in path): return fnd if salt.utils.url.is_escaped(path): path = salt.utils.url.unescape(path) elif ('?' in path): hcomps = path.split('?') ...
'Serve up a chunk of a file'
def serve_file(self, load):
ret = {'data': '', 'dest': ''} if ('env' in load): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0...
'Common code for hashing and stating files'
def __file_hash_and_stat(self, load):
if ('env' in load): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be r...
'Return the hash of a given file'
def file_hash(self, load):
try: return self.__file_hash_and_stat(load)[0] except (IndexError, TypeError): return ''
'Return the hash and stat result of a given file'
def file_hash_and_stat(self, load):
try: return self.__file_hash_and_stat(load) except (IndexError, TypeError): return ('', None)
'Deletes the file_lists cache files'
def clear_file_list_cache(self, load):
if ('env' in load): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will ...
'Return a list of files from the dominant environment'
def file_list(self, load):
if ('env' in load): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will ...
'List all emptydirs in the given environment'
def file_list_emptydirs(self, load):
if ('env' in load): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will ...
'List all directories in the given environment'
def dir_list(self, load):
if ('env' in load): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will ...
'Return a list of symlinked files and dirs'
def symlink_list(self, load):
if ('env' in load): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will ...
'Emulate the channel send method, the tries and timeout are not used'
def send(self, load, tries=None, timeout=None, raw=False):
if ('cmd' not in load): log.error('Malformed request, no cmd: {0}'.format(load)) return {} cmd = load['cmd'].lstrip('_') if (cmd in self.cmd_stub): return self.cmd_stub[cmd] if (cmd == 'file_envs'): return self.fs.envs() if (not hasattr(self.fs, cmd)): ...
'Return a friendly name for the database, e.g. \'MySQL\' or \'SQLite\'. Used in logging output.'
@classmethod @abc.abstractmethod def _db_name(cls):
pass
'Yield a PEP 249 compliant Cursor as a context manager.'
@abc.abstractmethod def _get_cursor(self):
pass
'This function normalizes the config block into a set of queries we can use. The return is a list of consistently laid out dicts.'
def extract_queries(self, args, kwargs):
qbuffer = [] qbuffer.extend([[None, s] for s in args]) klist = list(kwargs.keys()) klist.sort() qbuffer.extend([[k, kwargs[k]] for k in klist]) qbuffer = [x for x in qbuffer if ((isinstance(x[1], six.string_types) and len(x[1])) or (isinstance(x[1], (list, tuple)) and (len(x[1]) > 0) and x[1][0]...
'Set self.focus for kwarg queries'
def enter_root(self, root):
if root: self.result[root] = self.focus = {} else: self.focus = self.result
'The primary purpose of this function is to store the sql field list and the depth to which we process.'
def process_fields(self, field_names, depth):
self.field_names = field_names self.num_fields = len(field_names) if ((depth == 0) or (depth >= self.num_fields)): self.depth = (self.num_fields - 1) else: self.depth = depth
'This function takes a list of database results and iterates over, merging them into a dict form.'
def process_results(self, rows):
listify = OrderedDict() listify_dicts = OrderedDict() for ret in rows: crd = self.focus for i in range(0, (self.depth - 1)): if ((i + 1) in self.with_lists): if (id(crd) not in listify): listify[id(crd)] = [] listify_dicts[i...
'Execute queries, merge and return as a dict.'
def fetch(self, minion_id, pillar, *args, **kwargs):
db_name = self._db_name() log.info('Querying {0} for information for {1}'.format(db_name, minion_id)) qbuffer = self.extract_queries(args, kwargs) with self._get_cursor() as cursor: for (root, details) in qbuffer: cursor.execute(details['query'], (minion_id,)) ...
'Return a future which will contain the pillar data from the master'
@tornado.gen.coroutine def compile_pillar(self):
load = {'id': self.minion_id, 'grains': self.grains, 'saltenv': self.opts['environment'], 'pillarenv': self.opts['pillarenv'], 'pillar_override': self.pillar_override, 'ver': '2', 'cmd': '_pillar'} if self.ext: load['ext'] = self.ext try: ret_pillar = (yield self.channel.crypted_transfer_dec...
'Return the pillar data from the master'
def compile_pillar(self):
load = {'id': self.minion_id, 'grains': self.grains, 'saltenv': self.opts['environment'], 'pillarenv': self.opts['pillarenv'], 'pillar_override': self.pillar_override, 'ver': '2', 'cmd': '_pillar'} if self.ext: load['ext'] = self.ext ret_pillar = self.channel.crypted_transfer_decode_dictentry(load, ...
'Return the path to the cache file for the minion. Used only for disk-based backends'
def _minion_cache_path(self, minion_id):
return os.path.join(self.opts['cachedir'], 'pillar_cache', minion_id)
'In the event of a cache miss, we need to incur the overhead of caching a new pillar.'
def fetch_pillar(self):
log.debug('Pillar cache getting external pillar with ext: {0}'.format(self.ext)) fresh_pillar = Pillar(self.opts, self.grains, self.minion_id, self.saltenv, ext=self.ext, functions=self.functions, pillar_override=self.pillar_override, pillarenv=self.pillarenv) return fresh_pillar.compil...
'Check to see if the on demand external pillar is allowed'
def __valid_on_demand_ext_pillar(self, opts):
if (not isinstance(self.ext, dict)): log.error('On-demand pillar %s is not formatted as a dictionary', self.ext) return False on_demand = opts.get('on_demand_ext_pillar', []) try: invalid_on_demand = set([x for x in self.ext if (x not in on_demand)]) excep...
'Gather the lists of available sls data from the master'
def __gather_avail(self):
avail = {} for saltenv in self._get_envs(): avail[saltenv] = self.client.list_states(saltenv) return avail
'The options need to be altered to conform to the file client'
def __gen_opts(self, opts_in, grains, saltenv=None, ext=None, pillarenv=None):
opts = copy.deepcopy(opts_in) opts['file_roots'] = opts['pillar_roots'] opts['file_client'] = 'local' if (not grains): opts['grains'] = {} else: opts['grains'] = grains opts['environment'] = (saltenv if (saltenv is not None) else opts.get('environment')) opts['pillarenv'] = (...
'Pull the file server environments out of the master options'
def _get_envs(self):
envs = set(['base']) if ('file_roots' in self.opts): envs.update(list(self.opts['file_roots'])) return envs
'Gather the top files'
def get_tops(self):
tops = collections.defaultdict(list) include = collections.defaultdict(list) done = collections.defaultdict(list) errors = [] try: if self.opts['pillarenv']: if (self.opts['pillarenv'] not in self.opts['file_roots']): log.debug("pillarenv '%s' not found ...
'Cleanly merge the top files'
def merge_tops(self, tops):
top = collections.defaultdict(OrderedDict) orders = collections.defaultdict(OrderedDict) for ctops in six.itervalues(tops): for ctop in ctops: for (saltenv, targets) in six.iteritems(ctop): if (saltenv == 'include'): continue for tgt in...
'Returns the sorted high data from the merged top files'
def sort_top_targets(self, top, orders):
sorted_top = collections.defaultdict(OrderedDict) for (saltenv, targets) in six.iteritems(top): sorted_targets = sorted(targets, key=(lambda target: orders[saltenv][target])) for target in sorted_targets: sorted_top[saltenv][target] = targets[target] return sorted_top
'Returns the high data derived from the top file'
def get_top(self):
(tops, errors) = self.get_tops() try: merged_tops = self.merge_tops(tops) except TypeError as err: merged_tops = OrderedDict() errors.append('Error encountered while rendering pillar top file.') return (merged_tops, errors)
'Search through the top high data for matches and return the states that this minion needs to execute. Returns: {\'saltenv\': [\'state1\', \'state2\', ...]}'
def top_matches(self, top):
matches = {} for (saltenv, body) in six.iteritems(top): if self.opts['pillarenv']: if (saltenv != self.opts['pillarenv']): continue for (match, data) in six.iteritems(body): if self.matcher.confirm_top(match, data, self.opts.get('nodegroups', {})): ...
'Collect a single pillar sls file and render it'
def render_pstate(self, sls, saltenv, mods, defaults=None):
if (defaults is None): defaults = {} err = '' errors = [] fn_ = self.client.get_state(sls, saltenv).get('dest', False) if (not fn_): if (sls in self.ignored_pillars.get(saltenv, [])): log.debug("Skipping ignored and missing SLS '{0}' in environment ...
'Extract the sls pillar files from the matches and render them into the pillar'
def render_pillar(self, matches, errors=None):
pillar = copy.copy(self.pillar_override) if (errors is None): errors = [] for (saltenv, pstates) in six.iteritems(matches): pstatefiles = [] mods = set() for sls_match in pstates: matched_pstates = [] try: matched_pstates = fnmatch.filt...
'Builds actual pillar data structure and updates the ``pillar`` variable'
def _external_pillar_data(self, pillar, val, pillar_dirs, key):
ext = None if isinstance(val, dict): ext = self.ext_pillars[key](self.minion_id, pillar, **val) elif isinstance(val, list): if (key == 'git'): ext = self.ext_pillars[key](self.minion_id, val, pillar_dirs) else: ext = self.ext_pillars[key](self.minion_id, pilla...
'Render the external pillar data'
def ext_pillar(self, pillar, pillar_dirs, errors=None):
if (errors is None): errors = [] try: if (self.ext and ('git' in self.ext) and (self.opts.get('__role') != 'minion')): import salt.utils.gitfs from salt.pillar.git_pillar import PER_REMOTE_OVERRIDES git_pillar = salt.utils.gitfs.GitPillar(self.opts) ...
'Render the pillar data and return'
def compile_pillar(self, ext=True, pillar_dirs=None):
(top, top_errors) = self.get_top() if ext: if self.opts.get('ext_pillar_first', False): (self.opts['pillar'], errors) = self.ext_pillar(self.pillar_override, pillar_dirs) self.rend = salt.loader.render(self.opts, self.functions) matches = self.top_matches(top) ...
'Decrypt the specified pillar dictionary items, if configured to do so'
def decrypt_pillar(self, pillar):
errors = [] if self.opts.get('decrypt_pillar'): decrypt_pillar = self.opts['decrypt_pillar'] if (not isinstance(decrypt_pillar, dict)): decrypt_pillar = salt.utils.repack_dictlist(self.opts['decrypt_pillar']) if (not decrypt_pillar): errors.append('decrypt_pillar ...
'Try to initialize the SVN repo object'
def __init__(self, branch, repo_location, root, opts):
repo_hash = hashlib.md5(repo_location).hexdigest() repo_dir = os.path.join(opts['cachedir'], 'pillar_svnfs', repo_hash) self.branch = branch self.root = root self.repo_dir = repo_dir self.repo_location = repo_location if (not os.path.isdir(repo_dir)): os.makedirs(repo_dir) lo...
'Returns the directory of the pillars (repo cache + branch + root)'
def pillar_dir(self):
repo_dir = self.repo_dir root = self.root branch = self.branch if ((branch == 'trunk') or (branch == 'base')): working_dir = os.path.join(repo_dir, 'trunk', root) if (not os.path.isdir(working_dir)): log.error('Could not find {0}/trunk/{1}'.format(self.repo_location,...
'Returns options used for the MySQL connection.'
def _get_options(self):
defaults = {'host': 'localhost', 'user': 'salt', 'pass': 'salt', 'db': 'salt', 'port': 3306, 'ssl': {}} _options = {} _opts = __opts__.get('mysql', {}) for attr in defaults: if (attr not in _opts): log.debug('Using default for MySQL {0}'.format(attr)) _options...
'Yield a MySQL cursor'
@contextmanager def _get_cursor(self):
_options = self._get_options() conn = MySQLdb.connect(host=_options['host'], user=_options['user'], passwd=_options['pass'], db=_options['db'], port=_options['port'], ssl=_options['ssl']) cursor = conn.cursor() try: (yield cursor) except MySQLdb.DatabaseError as err: log.exception('E...
'This function normalizes the config block into a set of queries we can use. The return is a list of consistently laid out dicts.'
def extract_queries(self, args, kwargs):
return super(MySQLExtPillar, self).extract_queries(args, kwargs)
'Returns options used for the SQLCipher connection.'
def _get_options(self):
defaults = {'database': '/var/lib/salt/pillar-sqlcipher.db', 'pass': 'strong_pass_phrase', 'timeout': 5.0} _options = {} _opts = __opts__.get('sqlcipher', {}) for attr in defaults: if (attr not in _opts): log.debug('Using default for SQLCipher pillar %s', attr) ...
'Yield a SQLCipher cursor'
@contextmanager def _get_cursor(self):
_options = self._get_options() conn = sqlcipher.connect(_options.get('database'), timeout=float(_options.get('timeout'))) conn.execute('pragma key="{0}"'.format(_options.get('pass'))) cursor = conn.cursor() try: (yield cursor) except sqlcipher.Error as err: log.exception('Erro...
'Initialize a hg repo (or open it if it already exists)'
def __init__(self, repo_uri):
self.repo_uri = repo_uri cachedir = os.path.join(__opts__['cachedir'], 'hg_pillar') hash_type = getattr(hashlib, __opts__.get('hash_type', 'md5')) if six.PY2: repo_hash = hash_type(repo_uri).hexdigest() else: repo_hash = hash_type(salt.utils.stringutils.to_bytes(repo_uri)).hexdigest(...
'Ensure we are using the latest revision in the hg repository'
def update(self, branch='default'):
log.debug('Updating hg repo from hg_pillar module (pull)') self.repo.pull() log.debug('Updating hg repo from hg_pillar module (update)') self.repo.update(branch, clean=True)
'Cleanup mercurial command server'
def close(self):
self.repo.close()
'Try to initialize the Git repo object'
def __init__(self, branch, repo_location, opts):
self.branch = self.map_branch(branch, opts) self.rp_location = repo_location self.opts = opts self._envs = set() self.working_dir = '' self.repo = None hash_type = getattr(hashlib, opts['hash_type']) hash_str = '{0} {1}'.format(self.branch, self.rp_location) repo_hash = hash_type(...
'Ensure you are following the latest changes on the remote Return boolean whether it worked'
def update(self):
try: log.debug("Legacy git_pillar: Updating '%s'", self.rp_location) self.repo.git.fetch() except git.exc.GitCommandError as exc: log.error('Unable to fetch the latest changes from remote %s: %s', self.rp_location, exc) return False try: ...
'Return a list of refs that can be used as environments'
def envs(self):
if isinstance(self.repo, git.Repo): remote = self.repo.remote() for ref in self.repo.refs: parted = ref.name.partition('/') short = (parted[2] if parted[2] else parted[0]) if isinstance(ref, git.Head): if (short == 'master'): sh...
'Returns options used for the POSTGRES connection.'
def _get_options(self):
defaults = {'host': 'localhost', 'user': 'salt', 'pass': 'salt', 'db': 'salt', 'port': 5432} _options = {} _opts = __opts__.get('postgres', {}) for attr in defaults: if (attr not in _opts): log.debug('Using default for POSTGRES {0}'.format(attr)) _options[attr...
'Yield a POSTGRES cursor'
@contextmanager def _get_cursor(self):
_options = self._get_options() conn = psycopg2.connect(host=_options['host'], user=_options['user'], password=_options['pass'], dbname=_options['db']) cursor = conn.cursor() try: (yield cursor) log.debug('Connected to POSTGRES DB') except psycopg2.DatabaseError as err: ...
'This function normalizes the config block into a set of queries we can use. The return is a list of consistently laid out dicts.'
def extract_queries(self, args, kwargs):
return super(POSTGRESExtPillar, self).extract_queries(args, kwargs)
'Returns options used for the SQLite3 connection.'
def _get_options(self):
defaults = {'database': '/var/lib/salt/pillar.db', 'timeout': 5.0} _options = {} _opts = {} if (('sqlite3' in __opts__) and ('database' in __opts__['sqlite3'])): _opts = __opts__.get('sqlite3', {}) for attr in defaults: if (attr not in _opts): log.debug('Using default ...
'Yield a SQLite3 cursor'
@contextmanager def _get_cursor(self):
_options = self._get_options() conn = sqlite3.connect(_options.get('database'), timeout=float(_options.get('timeout'))) cursor = conn.cursor() try: (yield cursor) except sqlite3.Error as err: log.exception('Error in ext_pillar SQLite3: {0}'.format(err.args)) finally: ...
'Run the logic for saltkey'
def run(self):
self._update_opts() cmd = self.opts[u'fun'] veri = None ret = None try: if (cmd in (u'accept', u'reject', u'delete')): ret = self._run_cmd(u'name_match') if (not isinstance(ret, dict)): salt.output.display_output(ret, u'key', opts=self.opts) ...
'Call the given function on all backend keys'
def _call_all(self, fun, *args):
for kback in self.keys: print(kback) getattr(self.keys[kback], fun)(*args)
'Return the minion keys directory paths'
def _check_minions_directories(self):
minions_accepted = os.path.join(self.opts[u'pki_dir'], self.ACC) minions_pre = os.path.join(self.opts[u'pki_dir'], self.PEND) minions_rejected = os.path.join(self.opts[u'pki_dir'], self.REJ) minions_denied = os.path.join(self.opts[u'pki_dir'], self.DEN) return (minions_accepted, minions_pre, minions...
'Generate minion RSA public keypair'
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
(keydir, keyname, keysize, user) = self._get_key_attrs(keydir, keyname, keysize, user) salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase) return salt.utils.pem_finger(os.path.join(keydir, (keyname + u'.pub')))
'Generate master public-key-signature'
def gen_signature(self, privkey, pubkey, sig_path):
return salt.crypt.gen_signature(privkey, pubkey, sig_path, self.passphrase)
'Generate master public-key-signature'
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
if pub: if (not os.path.isfile(pub)): return u'Public-key {0} does not exist'.format(pub) else: mpub = ((self.opts[u'pki_dir'] + u'/') + u'master.pub') if os.path.isfile(mpub): pub = mpub if priv: if (not os.path.isfile(priv)): ...
'Check the minion cache to make sure that old minion data is cleared Optionally, pass in a list of minions which should have their caches preserved. To preserve all caches, set __opts__[\'preserve_minion_cache\']'
def check_minion_cache(self, preserve_minions=None):
if (preserve_minions is None): preserve_minions = [] keys = self.list_keys() minions = [] for (key, val) in six.iteritems(keys): minions.extend(val) if ((not self.opts.get(u'preserve_minion_cache', False)) or (not preserve_minions)): m_cache = os.path.join(self.opts[u'cachedi...
'Log if the master is not running :rtype: bool :return: Whether or not the master is running'
def check_master(self):
if (not os.path.exists(os.path.join(self.opts[u'sock_dir'], u'publish_pull.ipc'))): return False return True
'Accept a glob which to match the of a key and return the key\'s location'
def name_match(self, match, full=False):
if full: matches = self.all_keys() else: matches = self.list_keys() ret = {} if ((u',' in match) and isinstance(match, six.string_types)): match = match.split(u',') for (status, keys) in six.iteritems(matches): for key in salt.utils.isorted(keys): if isins...
'Accept a dictionary of keys and return the current state of the specified keys'
def dict_match(self, match_dict):
ret = {} cur_keys = self.list_keys() for (status, keys) in six.iteritems(match_dict): for key in salt.utils.isorted(keys): for keydir in (self.ACC, self.PEND, self.REJ, self.DEN): if (keydir and fnmatch.filter(cur_keys.get(keydir, []), key)): ret.setde...
'Return a dict of local keys'
def local_keys(self):
ret = {u'local': []} for fn_ in salt.utils.isorted(os.listdir(self.opts[u'pki_dir'])): if (fn_.endswith(u'.pub') or fn_.endswith(u'.pem')): path = os.path.join(self.opts[u'pki_dir'], fn_) if os.path.isfile(path): ret[u'local'].append(fn_) return ret
'Return a dict of managed keys and what the key status are'
def list_keys(self):
key_dirs = [] key_dirs = self._check_minions_directories() ret = {} for dir_ in key_dirs: if (dir_ is None): continue ret[os.path.basename(dir_)] = [] try: for fn_ in salt.utils.isorted(os.listdir(dir_)): if (not fn_.startswith(u'.')): ...