desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Find the specified file in the specified environment'
| def find_file(self, path, tgt_env):
| tree = self.get_tree(tgt_env)
if (not tree):
return (None, None, None)
blob = None
depth = 0
while True:
depth += 1
if (depth > SYMLINK_RECURSE_DEPTH):
blob = None
break
try:
file_blob = (tree / path)
if stat.S_ISLNK(fil... |
'Return the configured refspecs'
| def get_refspecs(self):
| refspecs = self.repo.git.config('--get-all', 'remote.origin.fetch')
return [x.strip() for x in refspecs.splitlines()]
|
'Return a git.Tree object matching a head ref fetched into
refs/remotes/origin/'
| def get_tree_from_branch(self, ref):
| try:
return git.RemoteReference(self.repo, 'refs/remotes/origin/{0}'.format(ref)).commit.tree
except ValueError:
return None
|
'Return a git.Tree object matching a tag ref fetched into refs/tags/'
| def get_tree_from_tag(self, ref):
| try:
return git.TagReference(self.repo, 'refs/tags/{0}'.format(ref)).commit.tree
except ValueError:
return None
|
'Return a git.Tree object matching a SHA'
| def get_tree_from_sha(self, ref):
| try:
return self.repo.rev_parse(ref).tree
except (gitdb.exc.ODBError, AttributeError):
return None
|
'Using the blob object, write the file to the destination path'
| def write_file(self, blob, dest):
| with salt.utils.files.fopen(dest, 'wb+') as fp_:
blob.stream_data(fp_)
|
'Add the specified refspecs to the "origin" remote'
| def add_refspecs(self, *refspecs):
| for refspec in refspecs:
try:
self.repo.config.set_multivar('remote.origin.fetch', 'FOO', refspec)
log.debug("Added refspec '%s' to %s remote '%s'", refspec, self.role, self.id)
except Exception as exc:
log.error("Failed to add refspec ... |
'Checkout the configured branch/tag'
| def checkout(self):
| tgt_ref = self.get_checkout_target()
local_ref = ('refs/heads/' + tgt_ref)
remote_ref = ('refs/remotes/origin/' + tgt_ref)
tag_ref = ('refs/tags/' + tgt_ref)
try:
local_head = self.repo.lookup_reference('HEAD')
except KeyError:
log.warning("HEAD not present in %s r... |
'Clean stale local refs so they don\'t appear as fileserver environments'
| def clean_stale_refs(self, local_refs=None):
| if (self.credentials is not None):
log.debug("pygit2 does not support detecting stale refs for authenticated remotes, saltenvs will not reflect branches/tags removed from remote '%s'", self.id)
return []
return super(Pygit2, self).clean_stale... |
'Initialize/attach to a remote using pygit2. Return a boolean which
will let the calling function know whether or not a new repo was
initialized by this function.'
| def init_remote(self):
| new = False
if (not os.listdir(self.cachedir)):
self.repo = pygit2.init_repository(self.cachedir)
new = True
else:
try:
try:
self.repo = pygit2.Repository(self.cachedir)
except GitError as exc:
import pwd
if ("Er... |
'Get a list of directories for the target environment using pygit2'
| def dir_list(self, tgt_env):
| def _traverse(tree, blobs, prefix):
'\n Traverse through a pygit2 Tree object recursively, accumulating all\n the empty directories within it in the "blobs" list\n ... |
'Check the refs and return a list of the ones which can be used as salt
environments.'
| def envs(self):
| ref_paths = self.repo.listall_references()
return self._get_envs_from_ref_paths(ref_paths)
|
'Fetch the repo. If the local copy was updated, return True. If the
local copy was already up-to-date, return False.'
| def _fetch(self):
| origin = self.repo.remotes[0]
refs_pre = self.repo.listall_references()
fetch_kwargs = {}
if (self.remotecallbacks is not None):
fetch_kwargs['callbacks'] = self.remotecallbacks
elif (self.credentials is not None):
origin.credentials = self.credentials
try:
fetch_results ... |
'Get file list for the target environment using pygit2'
| def file_list(self, tgt_env):
| def _traverse(tree, blobs, prefix):
'\n Traverse through a pygit2 Tree object recursively, accumulating all\n the file paths and symlink info in the "blobs" dict\n... |
'Find the specified file in the specified environment'
| def find_file(self, path, tgt_env):
| tree = self.get_tree(tgt_env)
if (not tree):
return (None, None, None)
blob = None
mode = None
depth = 0
while True:
depth += 1
if (depth > SYMLINK_RECURSE_DEPTH):
blob = None
break
try:
entry = tree[path]
mode = ent... |
'Return the configured refspecs'
| def get_refspecs(self):
| if (not [x for x in self.repo.config if x.startswith('remote.origin.')]):
raise GitRemoteError("'origin' remote not not present")
return list(self.repo.config.get_multivar('remote.origin.fetch'))
|
'Return a pygit2.Tree object matching a head ref fetched into
refs/remotes/origin/'
| def get_tree_from_branch(self, ref):
| try:
return self.repo.lookup_reference('refs/remotes/origin/{0}'.format(ref)).get_object().tree
except KeyError:
return None
|
'Return a pygit2.Tree object matching a tag ref fetched into refs/tags/'
| def get_tree_from_tag(self, ref):
| try:
return self.repo.lookup_reference('refs/tags/{0}'.format(ref)).get_object().tree
except KeyError:
return None
|
'Return a pygit2.Tree object matching a SHA'
| def get_tree_from_sha(self, ref):
| try:
return self.repo.revparse_single(ref).tree
except (KeyError, TypeError, ValueError, AttributeError):
return None
|
'Assign attributes for pygit2 callbacks'
| def setup_callbacks(self):
| pygit2_version = pygit2.__version__
if (distutils.version.LooseVersion(pygit2_version) >= distutils.version.LooseVersion('0.23.2')):
self.remotecallbacks = pygit2.RemoteCallbacks(credentials=self.credentials)
if (not self.ssl_verify):
self.remotecallbacks.certificate_check = (lambda ... |
'Check the username and password/keypair info for validity. If valid,
set a \'credentials\' attribute consisting of the appropriate Pygit2
credentials object. Return False if a required auth param is not
present. Return True if the required auth parameters are present (or
auth is not configured), otherwise failhard if ... | def verify_auth(self):
| self.credentials = None
if os.path.isabs(self.url):
return True
elif (not any((getattr(self, x, None) for x in AUTH_PARAMS))):
return True
def _incomplete_auth(missing):
'\n Helper function to log errors about missi... |
'Using the blob object, write the file to the destination path'
| def write_file(self, blob, dest):
| with salt.utils.files.fopen(dest, 'wb+') as fp_:
fp_.write(blob.data)
|
'IMPORTANT: If specifying a cache_root, understand that this is also
where the remotes will be cloned. A non-default cache_root is only
really designed right now for winrepo, as its repos need to be checked
out into the winrepo locations and not within the cachedir.'
| def __init__(self, opts, valid_providers=VALID_PROVIDERS, cache_root=None):
| self.opts = opts
self.valid_providers = valid_providers
self.get_provider()
if (cache_root is not None):
self.cache_root = self.remote_root = cache_root
else:
self.cache_root = salt.utils.path.join(self.opts['cachedir'], self.role)
self.remote_root = salt.utils.path.join(self... |
'Initialize remotes'
| def init_remotes(self, remotes, per_remote_overrides, per_remote_only=PER_REMOTE_ONLY):
| override_params = copy.deepcopy(per_remote_overrides)
global_auth_params = ['{0}_{1}'.format(self.role, x) for x in AUTH_PARAMS if self.opts['{0}_{1}'.format(self.role, x)]]
if (self.provider in AUTH_PROVIDERS):
override_params += AUTH_PARAMS
elif global_auth_params:
msg = "{0} authen... |
'Remove cache directories for remotes no longer configured'
| def clear_old_remotes(self):
| try:
cachedir_ls = os.listdir(self.cache_root)
except OSError:
cachedir_ls = []
for repo in self.remotes:
try:
cachedir_ls.remove(repo.cachedir_basename)
except ValueError:
pass
to_remove = []
for item in cachedir_ls:
if (item in ('hash... |
'Completely clear cache'
| def clear_cache(self):
| errors = []
for rdir in (self.cache_root, self.file_list_cachedir):
if os.path.exists(rdir):
try:
shutil.rmtree(rdir)
except OSError as exc:
errors.append('Unable to delete {0}: {1}'.format(rdir, exc))
return errors
|
'Clear update.lk for all remotes'
| def clear_lock(self, remote=None, lock_type='update'):
| cleared = []
errors = []
for repo in self.remotes:
if remote:
try:
if (not fnmatch.fnmatch(repo.url, remote)):
continue
except TypeError:
if (not fnmatch.fnmatch(repo.url, six.text_type(remote))):
continu... |
'Fetch all remotes and return a boolean to let the calling function know
whether or not any remotes were updated in the process of fetching'
| def fetch_remotes(self):
| changed = False
for repo in self.remotes:
try:
if repo.fetch():
changed = True
except Exception as exc:
log.error("Exception caught while fetching %s remote '%s': %s", self.role, repo.id, exc, exc_info=True)
return changed
|
'Place an update.lk'
| def lock(self, remote=None):
| locked = []
errors = []
for repo in self.remotes:
if remote:
try:
if (not fnmatch.fnmatch(repo.url, remote)):
continue
except TypeError:
if (not fnmatch.fnmatch(repo.url, six.text_type(remote))):
continue... |
'Execute a git fetch on all of the repos and perform maintenance on the
fileserver cache.'
| def update(self):
| data = {'changed': False, 'backend': 'gitfs'}
data['changed'] = self.clear_old_remotes()
if self.fetch_remotes():
data['changed'] = True
refresh_env_cache = (self.opts['__role'] == 'minion')
if ((data['changed'] is True) or (not os.path.isfile(self.env_cache))):
env_cachedir = os.pat... |
'Determine which provider to use'
| def get_provider(self):
| if ('verified_{0}_provider'.format(self.role) in self.opts):
self.provider = self.opts['verified_{0}_provider'.format(self.role)]
else:
desired_provider = self.opts.get('{0}_provider'.format(self.role))
if (not desired_provider):
if self.verify_pygit2(quiet=True):
... |
'Check if GitPython is available and at a compatible version (>= 0.3.0)'
| def verify_gitpython(self, quiet=False):
| def _recommend():
if (HAS_PYGIT2 and ('pygit2' in self.valid_providers)):
log.error(_RECOMMEND_PYGIT2.format(self.role))
if (not HAS_GITPYTHON):
if (not quiet):
log.error('%s is configured but could not be loaded, is GitPython installed?', se... |
'Check if pygit2/libgit2 are available and at a compatible version.
Pygit2 must be at least 0.20.3 and libgit2 must be at least 0.20.0.'
| def verify_pygit2(self, quiet=False):
| def _recommend():
if (HAS_GITPYTHON and ('gitpython' in self.valid_providers)):
log.error(_RECOMMEND_GITPYTHON.format(self.role))
if (not HAS_PYGIT2):
if (not quiet):
log.error('%s is configured but could not be loaded, are pygit2 and libg... |
'Write the remote_map.txt'
| def write_remote_map(self):
| remote_map = salt.utils.path.join(self.cache_root, 'remote_map.txt')
try:
with salt.utils.files.fopen(remote_map, 'w+') as fp_:
timestamp = datetime.now().strftime('%d %b %Y %H:%M:%S.%f')
fp_.write('# {0}_remote map as of {1}\n'.format(self.role, timestamp... |
'Common code for git_pillar/winrepo to handle locking and checking out
of a repo.'
| def do_checkout(self, repo):
| time_start = time.time()
while ((time.time() - time_start) <= 5):
try:
return repo.checkout()
except GitLockError as exc:
if (exc.errno == errno.EEXIST):
time.sleep(0.1)
continue
else:
log.error("Error %d e... |
'Return a list of all directories on the master'
| def dir_list(self, load):
| return self._file_lists(load, 'dirs')
|
'Return a list of refs that can be used as environments'
| def envs(self, ignore_cache=False):
| if (not ignore_cache):
cache_match = salt.fileserver.check_env_cache(self.opts, self.env_cache)
if (cache_match is not None):
return cache_match
ret = set()
for repo in self.remotes:
repo_envs = set()
if (not repo.disable_saltenv_mapping):
repo_envs.up... |
'Find the first file to match the path and ref, read the file out of git
and send the path to the newly cached file'
| def find_file(self, path, tgt_env='base', **kwargs):
| fnd = {'path': '', 'rel': ''}
if (os.path.isabs(path) or ((not salt.utils.stringutils.is_hex(tgt_env)) and (tgt_env not in self.envs()))):
return fnd
dest = salt.utils.path.join(self.cache_root, 'refs', tgt_env, path)
hashes_glob = salt.utils.path.join(self.hash_cachedir, tgt_env, '{0}.hash.*'.f... |
'Return a chunk from a file based on the data received'
| def serve_file(self, load, fnd):
| 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 file hash, the hash type is set in the master config file'
| def file_hash(self, load, fnd):
| 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 dict containing the file lists for files and dirs'
| def _file_lists(self, load, form):
| 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 all files on the file server in a specified
environment'
| def file_list(self, load):
| return self._file_lists(load, 'files')
|
'Return a list of all empty directories on the master'
| def file_list_emptydirs(self, load):
| return []
|
'Return a dict of all symlinks based on a given path in the repo'
| 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 ... |
'Checkout the targeted branches/tags from the git_pillar remotes'
| def checkout(self):
| self.pillar_dirs = OrderedDict()
self.pillar_linked_dirs = []
for repo in self.remotes:
cachedir = self.do_checkout(repo)
if (cachedir is not None):
if repo.env:
env = repo.env
else:
base_branch = self.opts['{0}_base'.format(self.role)]... |
'Ensure that the mountpoint is linked to the passed cachedir'
| def link_mountpoint(self, repo, cachedir):
| lcachelink = salt.utils.path.join(repo.linkdir, repo._mountpoint)
if (not os.path.islink(lcachelink)):
ldirname = os.path.dirname(lcachelink)
try:
os.symlink(cachedir, lcachelink)
except OSError as exc:
if (exc.errno == errno.ENOENT):
try:
... |
'Execute a git fetch on all of the repos. In this case, simply execute
self.fetch_remotes() from the parent class.
This function only exists to make the git_pillar update code in
master.py (salt.master.Maintenance.handle_git_pillar) less complicated,
once the legacy git_pillar code is purged we can remove this function... | def update(self):
| return self.fetch_remotes()
|
'Checkout the targeted branches/tags from the winrepo remotes'
| def checkout(self):
| self.winrepo_dirs = {}
for repo in self.remotes:
cachedir = self.do_checkout(repo)
if (cachedir is not None):
self.winrepo_dirs[repo.id] = cachedir
|
'Return minions found by looking at nodegroups'
| def _check_nodegroup_minions(self, expr, greedy):
| return self._check_compound_minions(nodegroup_comp(expr, self.opts['nodegroups']), DEFAULT_TARGET_DELIM, greedy)
|
'Return the minions found by looking via globs'
| def _check_glob_minions(self, expr, greedy):
| return fnmatch.filter(self._pki_minions(), expr)
|
'Return the minions found by looking via a list'
| def _check_list_minions(self, expr, greedy):
| if isinstance(expr, six.string_types):
expr = [m for m in expr.split(',') if m]
minions = self._pki_minions()
return [x for x in expr if (x in minions)]
|
'Return the minions found by looking via regular expressions'
| def _check_pcre_minions(self, expr, greedy):
| reg = re.compile(expr)
return [m for m in self._pki_minions() if reg.match(m)]
|
'Retreive complete minion list from PKI dir.
Respects cache if configured'
| def _pki_minions(self):
| minions = []
pki_cache_fn = os.path.join(self.opts['pki_dir'], self.acc, '.key_cache')
try:
if (self.opts['key_cache'] and os.path.exists(pki_cache_fn)):
log.debug('Returning cached minion list')
with salt.utils.files.fopen(pki_cache_fn) as fn_:
retur... |
'Helper function to search for minions in master caches
If \'greedy\' return accepted minions that matched by the condition or absend in the cache.
If not \'greedy\' return the only minions have cache data and matched by the condition.'
| def _check_cache_minions(self, expr, delimiter, greedy, search_type, regex_match=False, exact_match=False):
| cache_enabled = self.opts.get('minion_data_cache', False)
def list_cached_minions():
return self.cache.list('minions')
if greedy:
minions = []
for fn_ in salt.utils.isorted(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))):
if ((not fn_.startswith('.')) and os.pat... |
'Return the minions found by looking via grains'
| def _check_grain_minions(self, expr, delimiter, greedy):
| return self._check_cache_minions(expr, delimiter, greedy, 'grains')
|
'Return the minions found by looking via grains with PCRE'
| def _check_grain_pcre_minions(self, expr, delimiter, greedy):
| return self._check_cache_minions(expr, delimiter, greedy, 'grains', regex_match=True)
|
'Return the minions found by looking via pillar'
| def _check_pillar_minions(self, expr, delimiter, greedy):
| return self._check_cache_minions(expr, delimiter, greedy, 'pillar')
|
'Return the minions found by looking via pillar with PCRE'
| def _check_pillar_pcre_minions(self, expr, delimiter, greedy):
| return self._check_cache_minions(expr, delimiter, greedy, 'pillar', regex_match=True)
|
'Return the minions found by looking via pillar'
| def _check_pillar_exact_minions(self, expr, delimiter, greedy):
| return self._check_cache_minions(expr, delimiter, greedy, 'pillar', exact_match=True)
|
'Return the minions found by looking via ipcidr'
| def _check_ipcidr_minions(self, expr, greedy):
| cache_enabled = self.opts.get('minion_data_cache', False)
if greedy:
minions = self._pki_minions()
elif cache_enabled:
minions = self.cache.ls('minions')
else:
return []
if cache_enabled:
if greedy:
cminions = self.cache.ls('minions')
else:
... |
'Return the minions found by looking via range expression'
| def _check_range_minions(self, expr, greedy):
| if (not HAS_RANGE):
raise CommandExecutionError('Range matcher unavailable (unable to import seco.range, module most likely not installed)')
if (not hasattr(self, '_range')):
self._range = seco.range.Range(self.opts['range_server'])
try:
return self._... |
'Return the minions found by looking via compound matcher
Disable pillar glob matching'
| def _check_compound_pillar_exact_minions(self, expr, delimiter, greedy):
| return self._check_compound_minions(expr, delimiter, greedy, pillar_exact=True)
|
'Return the minions found by looking via compound matcher'
| def _check_compound_minions(self, expr, delimiter, greedy, pillar_exact=False):
| log.debug('_check_compound_minions({0}, {1}, {2}, {3})'.format(expr, delimiter, greedy, pillar_exact))
if ((not isinstance(expr, six.string_types)) and (not isinstance(expr, (list, tuple)))):
log.error('Compound target that is neither string, list nor tuple')
ret... |
'Return a set of all connected minion ids, optionally within a subset'
| def connected_ids(self, subset=None, show_ipv4=False, include_localhost=False):
| minions = set()
if self.opts.get('minion_data_cache', False):
search = self.cache.ls('minions')
if (search is None):
return minions
addrs = salt.utils.network.local_port_tcp(int(self.opts['publish_port']))
if (('127.0.0.1' in addrs) or ('0.0.0.0' in addrs)):
... |
'Return a list of all minions that have auth\'d'
| def _all_minions(self, expr=None):
| mlist = []
for fn_ in salt.utils.isorted(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))):
if ((not fn_.startswith('.')) and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_))):
mlist.append(fn_)
return mlist
|
'Check the passed regex against the available minions\' public keys
stored for authentication. This should return a set of ids which
match the regex, this will then be used to parse the returns to
make sure everyone has checked back in.'
| def check_minions(self, expr, tgt_type='glob', delimiter=DEFAULT_TARGET_DELIM, greedy=True):
| try:
if (expr is None):
expr = ''
check_func = getattr(self, '_check_{0}_minions'.format(tgt_type), None)
if (tgt_type in ('grain', 'grain_pcre', 'pillar', 'pillar_pcre', 'pillar_exact', 'compound', 'compound_pillar_exact')):
minions = check_func(expr, delimiter, gree... |
'Return a Bool. This function returns if the expression sent in is
within the scope of the valid expression'
| def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None):
| if (expr_form is not None):
salt.utils.warn_until('Fluorine', "the target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.")
tgt_type = expr_fo... |
'Validate a single regex to function comparison, the function argument
can be a list of functions. It is all or nothing for a list of
functions'
| def match_check(self, regex, fun):
| vals = []
if isinstance(fun, six.string_types):
fun = [fun]
for func in fun:
try:
if re.match(regex, func):
vals.append(True)
else:
vals.append(False)
except Exception:
log.error('Invalid regular expression: ... |
'Read in the form and determine which auth check routine to execute'
| def any_auth(self, form, auth_list, fun, arg, tgt=None, tgt_type='glob'):
| if (form == 'publish'):
return self.auth_check(auth_list, fun, arg, tgt, tgt_type)
return self.spec_check(auth_list, fun, form)
|
'Returns a bool which defines if the requested function is authorized.
Used to evaluate the standard structure under external master
authentication interfaces, like eauth, peer, peer_run, etc.'
| def auth_check(self, auth_list, funs, args, tgt, tgt_type='glob', groups=None, publish_validate=False, minions=None, whitelist=None):
| if self.opts.get('auth.enable_expanded_auth_matching', False):
return self.auth_check_expanded(auth_list, funs, args, tgt, tgt_type, groups, publish_validate)
if publish_validate:
v_tgt_type = tgt_type
if (tgt_type.lower() in ('pillar', 'pillar_pcre')):
v_tgt_type = 'pillar_e... |
'Returns a list of authorisation matchers that a user is eligible for.
This list is a combination of the provided personal matchers plus the
matchers of any group the user is in.'
| def fill_auth_list_from_groups(self, auth_provider, user_groups, auth_list):
| group_names = [item for item in auth_provider if item.endswith('%')]
if group_names:
for group_name in group_names:
if (group_name.rstrip('%') in user_groups):
for matcher in auth_provider[group_name]:
auth_list.append(matcher)
return auth_list
|
'Check special API permissions'
| def wheel_check(self, auth_list, fun):
| comps = fun.split('.')
if (len(comps) != 2):
return False
mod = comps[0]
fun = comps[1]
for ind in auth_list:
if isinstance(ind, six.string_types):
if (ind.startswith('@') and (ind[1:] == mod)):
return True
if (ind == '@wheel'):
... |
'Check special API permissions'
| def runner_check(self, auth_list, fun):
| comps = fun.split('.')
if (len(comps) != 2):
return False
mod = comps[0]
fun = comps[1]
for ind in auth_list:
if isinstance(ind, six.string_types):
if (ind.startswith('@') and (ind[1:] == mod)):
return True
if (ind == '@runners'):
... |
'Check special API permissions'
| def spec_check(self, auth_list, fun, form):
| if (form != 'cloud'):
comps = fun.split('.')
if (len(comps) != 2):
return False
mod = comps[0]
fun = comps[1]
else:
mod = fun
for ind in auth_list:
if isinstance(ind, six.string_types):
if (ind.startswith('@') and (ind[1:] == mod)):
... |
'Get pillar data for the targeted minions, either by fetching the
cached minion data on the master, or by compiling the minion\'s
pillar data on the master.
For runner modules that need access minion pillar data, this
function should be used instead of getting the pillar data by
executing the pillar module on the minio... | def get_minion_pillar(self):
| minion_pillars = {}
minion_grains = {}
minion_ids = self._tgt_to_list()
if any((arg for arg in [self.use_cached_grains, self.use_cached_pillar, self.grains_fallback, self.pillar_fallback])):
log.debug('Getting cached minion data')
(cached_minion_grains, cached_minion_pillars) = ... |
'Get grains data for the targeted minions, either by fetching the
cached minion data on the master, or by fetching the grains
directly on the minion.
By default, this function tries hard to get the pillar data:
- Try to get the cached minion grains if the master
has minion_data_cache: True
- If the grains data for the ... | def get_minion_grains(self):
| minion_grains = {}
minion_ids = self._tgt_to_list()
if any((arg for arg in [self.use_cached_grains, self.grains_fallback])):
log.debug('Getting cached minion data.')
(cached_minion_grains, cached_minion_pillars) = self._get_cached_minion_data(*minion_ids)
else:
cached_mi... |
'Get cached mine data for the targeted minions.'
| def get_cached_mine_data(self):
| mine_data = {}
minion_ids = self._tgt_to_list()
log.debug('Getting cached mine data for: {0}'.format(minion_ids))
mine_data = self._get_cached_mine_data(*minion_ids)
return mine_data
|
'Clear the cached data/files for the targeted minions.'
| def clear_cached_minion_data(self, clear_pillar=False, clear_grains=False, clear_mine=False, clear_mine_func=None):
| clear_what = []
if clear_pillar:
clear_what.append('pillar')
if clear_grains:
clear_what.append('grains')
if clear_mine:
clear_what.append('mine')
if (clear_mine_func is not None):
clear_what.append("mine_func: '{0}'".format(clear_mine_func))
if (not len(clear_... |
'main loop that fires the event every second'
| def run(self):
| context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.setsockopt(zmq.LINGER, 100)
socket.bind(('ipc://' + self.timer_sock))
count = 0
log.debug('ConCache-Timer started')
while (not self.stopped.wait(1)):
socket.send(self.serial.dumps(count))
count += 1
if... |
'Sets up the zmq-connection to the ConCache'
| def __init__(self, opts, log_queue=None):
| super(CacheWorker, self).__init__(log_queue=log_queue)
self.opts = opts
|
'Gather currently connected minions and update the cache'
| def run(self):
| new_mins = list(salt.utils.minions.CkMinions(self.opts).connected_ids())
cc = cache_cli(self.opts)
cc.get_cached()
cc.put_cache([new_mins])
log.debug('ConCache CacheWorker update finished')
|
'starts the timer and inits the cache itself'
| def __init__(self, opts, log_queue=None):
| super(ConnectedCache, self).__init__(log_queue=log_queue)
log.debug('ConCache initializing...')
self.opts = opts
self.minions = []
self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc')
self.update_sock = os.path.join(self.opts['sock_dir'], 'con_upd.ipc')
self.upd_t_sock =... |
'handle signals and shutdown'
| def signal_handler(self, sig, frame):
| self.stop()
|
'remove sockets on shutdown'
| def cleanup(self):
| log.debug('ConCache cleaning up')
if os.path.exists(self.cache_sock):
os.remove(self.cache_sock)
if os.path.exists(self.update_sock):
os.remove(self.update_sock)
if os.path.exists(self.upd_t_sock):
os.remove(self.upd_t_sock)
|
'secure the sockets for root-only access'
| def secure(self):
| log.debug('ConCache securing sockets')
if os.path.exists(self.cache_sock):
os.chmod(self.cache_sock, 384)
if os.path.exists(self.update_sock):
os.chmod(self.update_sock, 384)
if os.path.exists(self.upd_t_sock):
os.chmod(self.upd_t_sock, 384)
|
'shutdown cache process'
| def stop(self):
| self.cleanup()
if self.running:
self.running = False
self.timer_stop.set()
self.timer.join()
|
'Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers'
| def run(self):
| context = zmq.Context()
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
creq_in.bind(('ipc://' + self.cache_sock))
cupd_in = context.socket(zmq.SUB)
cupd_in.setsockopt(zmq.SUBSCRIBE, '')
cupd_in.setsockopt(zmq.LINGER, 100)
cupd_in.bind(('ipc://' + self.update_sock))... |
'Make output look like libcloud output for consistency'
| def __init__(self, name, server, password=None):
| self.name = name
self.id = server['id']
self.image = server.get('image', {}).get('id', 'Boot From Volume')
self.size = server['flavor']['id']
self.state = server['state']
self._uuid = None
self.extra = {'metadata': server['metadata'], 'access_ip': server['accessIPv4']}
self.address... |
'Set up nova credentials'
| def __init__(self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs):
| if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs)
else:
self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_... |
'Return service catalog'
| def get_catalog(self):
| return self.catalog
|
'Make output look like libcloud output for consistency'
| def server_show_libcloud(self, uuid):
| server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if (not hasattr(self, 'password')):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
|
'Boot a cloud server.'
| def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
| nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = (image_id or None)
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
... |
'Find a server by its name (libcloud)'
| def show_instance(self, name):
| return self.server_by_name(name)
|
'Change server(uuid\'s) root password'
| def root_password(self, server_id, password):
| nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
|
'Find a server by its name'
| def server_by_name(self, name):
| return self.server_show_libcloud(self.server_list().get(name, {}).get('id', ''))
|
'Organize information about a volume from the volume_id'
| def _volume_get(self, volume_id):
| if (self.volume_conn is None):
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments'... |
'List all block volumes'
| def volume_list(self, search_opts=None):
| if (self.volume_conn is None):
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {'name': volume.display_name, 'size': ... |
'Show one volume'
| def volume_show(self, name):
| if (self.volume_conn is None):
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(search_opts={'display_name': name})
volume = volumes[name]
return volume
|
'Create a block device'
| def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None):
| if (self.volume_conn is None):
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone)
return self._volume_get(respons... |
'Delete a block device'
| def volume_delete(self, name):
| if (self.volume_conn is None):
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.