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/key.py | Key.check_minion_cache | def check_minion_cache(self, preserve_minions=None):
'''
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']
'''
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('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion)) | python | def check_minion_cache(self, preserve_minions=None):
'''
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']
'''
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('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion)) | [
"def",
"check_minion_cache",
"(",
"self",
",",
"preserve_minions",
"=",
"None",
")",
":",
"if",
"preserve_minions",
"is",
"None",
":",
"preserve_minions",
"=",
"[",
"]",
"keys",
"=",
"self",
".",
"list_keys",
"(",
")",
"minions",
"=",
"[",
"]",
"for",
"k... | 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'] | [
"Check",
"the",
"minion",
"cache",
"to",
"make",
"sure",
"that",
"old",
"minion",
"data",
"is",
"cleared"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L418-L448 | train |
saltstack/salt | salt/key.py | Key.check_master | def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True | python | def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True | [
"def",
"check_master",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"opts",
"[",
"'sock_dir'",
"]",
",",
"'publish_pull.ipc'",
")",
")",
":",
"return",
"False",
"return",... | Log if the master is not running
:rtype: bool
:return: Whether or not the master is running | [
"Log",
"if",
"the",
"master",
"is",
"not",
"running"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L450-L464 | train |
saltstack/salt | salt/key.py | Key.name_match | def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret | python | def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret | [
"def",
"name_match",
"(",
"self",
",",
"match",
",",
"full",
"=",
"False",
")",
":",
"if",
"full",
":",
"matches",
"=",
"self",
".",
"all_keys",
"(",
")",
"else",
":",
"matches",
"=",
"self",
".",
"list_keys",
"(",
")",
"ret",
"=",
"{",
"}",
"if"... | Accept a glob which to match the of a key and return the key's location | [
"Accept",
"a",
"glob",
"which",
"to",
"match",
"the",
"of",
"a",
"key",
"and",
"return",
"the",
"key",
"s",
"location"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L466-L490 | train |
saltstack/salt | salt/key.py | Key.dict_match | def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret | python | def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret | [
"def",
"dict_match",
"(",
"self",
",",
"match_dict",
")",
":",
"ret",
"=",
"{",
"}",
"cur_keys",
"=",
"self",
".",
"list_keys",
"(",
")",
"for",
"status",
",",
"keys",
"in",
"six",
".",
"iteritems",
"(",
"match_dict",
")",
":",
"for",
"key",
"in",
... | Accept a dictionary of keys and return the current state of the
specified keys | [
"Accept",
"a",
"dictionary",
"of",
"keys",
"and",
"return",
"the",
"current",
"state",
"of",
"the",
"specified",
"keys"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L492-L504 | train |
saltstack/salt | salt/key.py | Key.local_keys | def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret | python | def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret | [
"def",
"local_keys",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"'local'",
":",
"[",
"]",
"}",
"for",
"fn_",
"in",
"salt",
".",
"utils",
".",
"data",
".",
"sorted_ignorecase",
"(",
"os",
".",
"listdir",
"(",
"self",
".",
"opts",
"[",
"'pki_dir'",
"]",... | Return a dict of local keys | [
"Return",
"a",
"dict",
"of",
"local",
"keys"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L506-L516 | train |
saltstack/salt | salt/key.py | Key.list_keys | def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
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.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret | python | def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
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.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret | [
"def",
"list_keys",
"(",
"self",
")",
":",
"key_dirs",
"=",
"self",
".",
"_check_minions_directories",
"(",
")",
"ret",
"=",
"{",
"}",
"for",
"dir_",
"in",
"key_dirs",
":",
"if",
"dir_",
"is",
"None",
":",
"continue",
"ret",
"[",
"os",
".",
"path",
"... | Return a dict of managed keys and what the key status are | [
"Return",
"a",
"dict",
"of",
"managed",
"keys",
"and",
"what",
"the",
"key",
"status",
"are"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L518-L540 | train |
saltstack/salt | salt/key.py | Key.all_keys | def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys | python | def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys | [
"def",
"all_keys",
"(",
"self",
")",
":",
"keys",
"=",
"self",
".",
"list_keys",
"(",
")",
"keys",
".",
"update",
"(",
"self",
".",
"local_keys",
"(",
")",
")",
"return",
"keys"
] | Merge managed keys with local keys | [
"Merge",
"managed",
"keys",
"with",
"local",
"keys"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L542-L548 | train |
saltstack/salt | salt/key.py | Key.list_status | def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret | python | def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret | [
"def",
"list_status",
"(",
"self",
",",
"match",
")",
":",
"acc",
",",
"pre",
",",
"rej",
",",
"den",
"=",
"self",
".",
"_check_minions_directories",
"(",
")",
"ret",
"=",
"{",
"}",
"if",
"match",
".",
"startswith",
"(",
"'acc'",
")",
":",
"ret",
"... | Return a dict of managed keys under a named status | [
"Return",
"a",
"dict",
"of",
"managed",
"keys",
"under",
"a",
"named",
"status"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L550-L582 | train |
saltstack/salt | salt/key.py | Key.key_str | def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret | python | def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret | [
"def",
"key_str",
"(",
"self",
",",
"match",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"status",
",",
"keys",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"name_match",
"(",
"match",
")",
")",
":",
"ret",
"[",
"status",
"]",
"=",
"{",
"}",
"fo... | Return the specified public key or keys based on a glob | [
"Return",
"the",
"specified",
"public",
"key",
"or",
"keys",
"based",
"on",
"a",
"glob"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L584-L596 | train |
saltstack/salt | salt/key.py | Key.accept | def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
) | python | def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
) | [
"def",
"accept",
"(",
"self",
",",
"match",
"=",
"None",
",",
"match_dict",
"=",
"None",
",",
"include_rejected",
"=",
"False",
",",
"include_denied",
"=",
"False",
")",
":",
"if",
"match",
"is",
"not",
"None",
":",
"matches",
"=",
"self",
".",
"name_m... | Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict". | [
"Accept",
"public",
"keys",
".",
"If",
"match",
"is",
"passed",
"it",
"is",
"evaluated",
"as",
"a",
"glob",
".",
"Pre",
"-",
"gathered",
"matches",
"can",
"also",
"be",
"passed",
"via",
"match_dict",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L612-L651 | train |
saltstack/salt | salt/key.py | Key.accept_all | def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys() | python | def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys() | [
"def",
"accept_all",
"(",
"self",
")",
":",
"keys",
"=",
"self",
".",
"list_keys",
"(",
")",
"for",
"key",
"in",
"keys",
"[",
"self",
".",
"PEND",
"]",
":",
"try",
":",
"shutil",
".",
"move",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".... | Accept all keys in pre | [
"Accept",
"all",
"keys",
"in",
"pre"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L653-L677 | train |
saltstack/salt | salt/key.py | Key.delete_key | def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
) | python | def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
) | [
"def",
"delete_key",
"(",
"self",
",",
"match",
"=",
"None",
",",
"match_dict",
"=",
"None",
",",
"preserve_minions",
"=",
"None",
",",
"revoke_auth",
"=",
"False",
")",
":",
"if",
"match",
"is",
"not",
"None",
":",
"matches",
"=",
"self",
".",
"name_m... | Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions | [
"Delete",
"public",
"keys",
".",
"If",
"match",
"is",
"passed",
"it",
"is",
"evaluated",
"as",
"a",
"glob",
".",
"Pre",
"-",
"gathered",
"matches",
"can",
"also",
"be",
"passed",
"via",
"match_dict",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L679-L729 | train |
saltstack/salt | salt/key.py | Key.delete_den | def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys() | python | def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys() | [
"def",
"delete_den",
"(",
"self",
")",
":",
"keys",
"=",
"self",
".",
"list_keys",
"(",
")",
"for",
"status",
",",
"keys",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"list_keys",
"(",
")",
")",
":",
"for",
"key",
"in",
"keys",
"[",
"self",
... | Delete all denied keys | [
"Delete",
"all",
"denied",
"keys"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L731-L748 | train |
saltstack/salt | salt/key.py | Key.delete_all | def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys() | python | def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys() | [
"def",
"delete_all",
"(",
"self",
")",
":",
"for",
"status",
",",
"keys",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"list_keys",
"(",
")",
")",
":",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
... | Delete all keys | [
"Delete",
"all",
"keys"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L750-L768 | train |
saltstack/salt | salt/key.py | Key.reject_all | def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys() | python | def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys() | [
"def",
"reject_all",
"(",
"self",
")",
":",
"keys",
"=",
"self",
".",
"list_keys",
"(",
")",
"for",
"key",
"in",
"keys",
"[",
"self",
".",
"PEND",
"]",
":",
"try",
":",
"shutil",
".",
"move",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".... | Reject all keys in pre | [
"Reject",
"all",
"keys",
"in",
"pre"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L814-L841 | train |
saltstack/salt | salt/key.py | Key.finger | def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret | python | def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret | [
"def",
"finger",
"(",
"self",
",",
"match",
",",
"hash_type",
"=",
"None",
")",
":",
"if",
"hash_type",
"is",
"None",
":",
"hash_type",
"=",
"__opts__",
"[",
"'hash_type'",
"]",
"matches",
"=",
"self",
".",
"name_match",
"(",
"match",
",",
"True",
")",... | Return the fingerprint for a specified key | [
"Return",
"the",
"fingerprint",
"for",
"a",
"specified",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L843-L860 | train |
saltstack/salt | salt/key.py | Key.finger_all | def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret | python | def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret | [
"def",
"finger_all",
"(",
"self",
",",
"hash_type",
"=",
"None",
")",
":",
"if",
"hash_type",
"is",
"None",
":",
"hash_type",
"=",
"__opts__",
"[",
"'hash_type'",
"]",
"ret",
"=",
"{",
"}",
"for",
"status",
",",
"keys",
"in",
"six",
".",
"iteritems",
... | Return fingerprints for all keys | [
"Return",
"fingerprints",
"for",
"all",
"keys"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L862-L878 | train |
saltstack/salt | salt/modules/tomcat.py | __catalina_home | def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False | python | def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False | [
"def",
"__catalina_home",
"(",
")",
":",
"locations",
"=",
"[",
"'/usr/share/tomcat*'",
",",
"'/opt/tomcat'",
"]",
"for",
"location",
"in",
"locations",
":",
"folders",
"=",
"glob",
".",
"glob",
"(",
"location",
")",
"if",
"folders",
":",
"for",
"catalina_ho... | Tomcat paths differ depending on packaging | [
"Tomcat",
"paths",
"differ",
"depending",
"on",
"packaging"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L119-L130 | train |
saltstack/salt | salt/modules/tomcat.py | _get_credentials | def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd'] | python | def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd'] | [
"def",
"_get_credentials",
"(",
")",
":",
"ret",
"=",
"{",
"'user'",
":",
"False",
",",
"'passwd'",
":",
"False",
"}",
"# Loop through opts, grains, and pillar",
"# Return the first acceptable configuration found",
"for",
"item",
"in",
"ret",
":",
"for",
"struct",
"... | Get the username and password from opts, grains, or pillar | [
"Get",
"the",
"username",
"and",
"password",
"from",
"opts",
"grains",
"or",
"pillar"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L133-L156 | train |
saltstack/salt | salt/modules/tomcat.py | _auth | def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest) | python | def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest) | [
"def",
"_auth",
"(",
"uri",
")",
":",
"user",
",",
"password",
"=",
"_get_credentials",
"(",
")",
"if",
"user",
"is",
"False",
"or",
"password",
"is",
"False",
":",
"return",
"False",
"basic",
"=",
"_HTTPBasicAuthHandler",
"(",
")",
"basic",
".",
"add_pa... | returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False | [
"returns",
"a",
"authentication",
"handler",
".",
"Get",
"user",
"&",
"password",
"from",
"grains",
"if",
"are",
"not",
"set",
"default",
"to",
"modules",
".",
"config",
".",
"option"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L159-L178 | train |
saltstack/salt | salt/modules/tomcat.py | extract_war_version | def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None | python | def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None | [
"def",
"extract_war_version",
"(",
"war",
")",
":",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"war",
")",
"war_package",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"basename",
")",
"[",
"0",
"]",
"# remove '.war'",
"version",
"=",
"r... | Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None | [
"Extract",
"the",
"version",
"from",
"the",
"war",
"file",
"name",
".",
"There",
"does",
"not",
"seem",
"to",
"be",
"a",
"standard",
"for",
"encoding",
"the",
"version",
"into",
"the",
"war",
"file",
"name",
"_"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L181-L198 | train |
saltstack/salt | salt/modules/tomcat.py | _wget | def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret | python | def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret | [
"def",
"_wget",
"(",
"cmd",
",",
"opts",
"=",
"None",
",",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"timeout",
"=",
"180",
")",
":",
"ret",
"=",
"{",
"'res'",
":",
"True",
",",
"'msg'",
":",
"[",
"]",
"}",
"# prepare authentication",
"auth",
... | A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
} | [
"A",
"private",
"function",
"used",
"to",
"issue",
"the",
"command",
"to",
"tomcat",
"via",
"the",
"manager",
"webapp"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L201-L265 | train |
saltstack/salt | salt/modules/tomcat.py | _simple_cmd | def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app) | python | def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app) | [
"def",
"_simple_cmd",
"(",
"cmd",
",",
"app",
",",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"timeout",
"=",
"180",
")",
":",
"try",
":",
"opts",
"=",
"{",
"'path'",
":",
"app",
",",
"'version'",
":",
"ls",
"(",
"url",
")",
"[",
"app",
"]",... | Simple command wrapper to commands that need only a path option | [
"Simple",
"command",
"wrapper",
"to",
"commands",
"that",
"need",
"only",
"a",
"path",
"option"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L268-L280 | train |
saltstack/salt | salt/modules/tomcat.py | ls | def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret | python | def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret | [
"def",
"ls",
"(",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"timeout",
"=",
"180",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"_wget",
"(",
"'list'",
",",
"''",
",",
"url",
",",
"timeout",
"=",
"timeout",
")",
"if",
"data",
"[",
"'res'",
... | list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager | [
"list",
"all",
"the",
"deployed",
"webapps"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L324-L358 | train |
saltstack/salt | salt/modules/tomcat.py | status_webapp | def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing' | python | def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing' | [
"def",
"status_webapp",
"(",
"app",
",",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"timeout",
"=",
"180",
")",
":",
"webapps",
"=",
"ls",
"(",
"url",
",",
"timeout",
"=",
"timeout",
")",
"for",
"i",
"in",
"webapps",
":",
"if",
"i",
"==",
"app... | return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager | [
"return",
"the",
"status",
"of",
"the",
"webapp",
"(",
"stopped",
"|",
"running",
"|",
"missing",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L449-L473 | train |
saltstack/salt | salt/modules/tomcat.py | serverinfo | def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret | python | def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret | [
"def",
"serverinfo",
"(",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"timeout",
"=",
"180",
")",
":",
"data",
"=",
"_wget",
"(",
"'serverinfo'",
",",
"{",
"}",
",",
"url",
",",
"timeout",
"=",
"timeout",
")",
"if",
"data",
"[",
"'res'",
"]",
"... | return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager | [
"return",
"details",
"about",
"the",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L476-L503 | train |
saltstack/salt | salt/modules/tomcat.py | deploy_war | def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res | python | def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res | [
"def",
"deploy_war",
"(",
"war",
",",
"context",
",",
"force",
"=",
"'no'",
",",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"saltenv",
"=",
"'base'",
",",
"timeout",
"=",
"180",
",",
"temp_war_location",
"=",
"None",
",",
"version",
"=",
"True",
"... | Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager | [
"Deploy",
"a",
"WAR",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L528-L635 | train |
saltstack/salt | salt/modules/tomcat.py | passwd | def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False | python | def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False | [
"def",
"passwd",
"(",
"passwd",
",",
"user",
"=",
"''",
",",
"alg",
"=",
"'sha1'",
",",
"realm",
"=",
"None",
")",
":",
"# Shouldn't it be SHA265 instead of SHA1?",
"digest",
"=",
"hasattr",
"(",
"hashlib",
",",
"alg",
")",
"and",
"getattr",
"(",
"hashlib"... | This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm' | [
"This",
"function",
"replaces",
"the",
"$CATALINA_HOME",
"/",
"bin",
"/",
"digest",
".",
"sh",
"script",
"convert",
"a",
"clear",
"-",
"text",
"password",
"to",
"the",
"$CATALINA_BASE",
"/",
"conf",
"/",
"tomcat",
"-",
"users",
".",
"xml",
"format"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L638-L663 | train |
saltstack/salt | salt/modules/tomcat.py | version | def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1] | python | def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1] | [
"def",
"version",
"(",
")",
":",
"cmd",
"=",
"__catalina_home",
"(",
")",
"+",
"'/bin/catalina.sh version'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"out",
":",
"if",
"not",
"lin... | Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version | [
"Return",
"server",
"version",
"from",
"catalina",
".",
"sh",
"version"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L667-L684 | train |
saltstack/salt | salt/modules/tomcat.py | fullversion | def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret | python | def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret | [
"def",
"fullversion",
"(",
")",
":",
"cmd",
"=",
"__catalina_home",
"(",
")",
"+",
"'/bin/catalina.sh version'",
"ret",
"=",
"{",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"ou... | Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion | [
"Return",
"all",
"server",
"information",
"from",
"catalina",
".",
"sh",
"version"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L687-L706 | train |
saltstack/salt | salt/modules/tomcat.py | signal | def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd) | python | def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd) | [
"def",
"signal",
"(",
"signal",
"=",
"None",
")",
":",
"valid_signals",
"=",
"{",
"'forcestop'",
":",
"'stop -force'",
",",
"'securestart'",
":",
"'start -security'",
",",
"'start'",
":",
"'start'",
",",
"'stop'",
":",
"'stop'",
"}",
"if",
"signal",
"not",
... | Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start | [
"Signals",
"catalina",
"to",
"start",
"stop",
"securestart",
"forcestop",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L709-L730 | train |
saltstack/salt | salt/returners/appoptics_return.py | _get_options | def _get_options(ret=None):
'''
Get the appoptics options from salt.
'''
attrs = {
'api_token': 'api_token',
'api_url': 'api_url',
'tags': 'tags',
'sls_states': 'sls_states'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
_options['api_url'] = _options.get('api_url', 'api.appoptics.com')
_options['sls_states'] = _options.get('sls_states', [])
_options['tags'] = _options.get('tags', {
'host_hostname_alias': __salt__['grains.get']('id')
})
log.debug('Retrieved appoptics options: %s', _options)
return _options | python | def _get_options(ret=None):
'''
Get the appoptics options from salt.
'''
attrs = {
'api_token': 'api_token',
'api_url': 'api_url',
'tags': 'tags',
'sls_states': 'sls_states'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
_options['api_url'] = _options.get('api_url', 'api.appoptics.com')
_options['sls_states'] = _options.get('sls_states', [])
_options['tags'] = _options.get('tags', {
'host_hostname_alias': __salt__['grains.get']('id')
})
log.debug('Retrieved appoptics options: %s', _options)
return _options | [
"def",
"_get_options",
"(",
"ret",
"=",
"None",
")",
":",
"attrs",
"=",
"{",
"'api_token'",
":",
"'api_token'",
",",
"'api_url'",
":",
"'api_url'",
",",
"'tags'",
":",
"'tags'",
",",
"'sls_states'",
":",
"'sls_states'",
"}",
"_options",
"=",
"salt",
".",
... | Get the appoptics options from salt. | [
"Get",
"the",
"appoptics",
"options",
"from",
"salt",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/appoptics_return.py#L98-L123 | train |
saltstack/salt | salt/returners/appoptics_return.py | _get_appoptics | def _get_appoptics(options):
'''
Return an appoptics connection object.
'''
conn = appoptics_metrics.connect(
options.get('api_token'),
sanitizer=appoptics_metrics.sanitize_metric_name,
hostname=options.get('api_url'))
log.info("Connected to appoptics.")
return conn | python | def _get_appoptics(options):
'''
Return an appoptics connection object.
'''
conn = appoptics_metrics.connect(
options.get('api_token'),
sanitizer=appoptics_metrics.sanitize_metric_name,
hostname=options.get('api_url'))
log.info("Connected to appoptics.")
return conn | [
"def",
"_get_appoptics",
"(",
"options",
")",
":",
"conn",
"=",
"appoptics_metrics",
".",
"connect",
"(",
"options",
".",
"get",
"(",
"'api_token'",
")",
",",
"sanitizer",
"=",
"appoptics_metrics",
".",
"sanitize_metric_name",
",",
"hostname",
"=",
"options",
... | Return an appoptics connection object. | [
"Return",
"an",
"appoptics",
"connection",
"object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/appoptics_return.py#L126-L135 | train |
saltstack/salt | salt/returners/appoptics_return.py | returner | def returner(ret):
'''
Parse the return data and return metrics to AppOptics.
For each state that's provided in the configuration, return tagged metrics for
the result of that state if it's present.
'''
options = _get_options(ret)
states_to_report = ['state.highstate']
if options.get('sls_states'):
states_to_report.append('state.sls')
if ret['fun'] in states_to_report:
tags = options.get('tags', {}).copy()
tags['state_type'] = ret['fun']
log.info("Tags for this run are %s", tags)
matched_states = set(ret['fun_args']).intersection(
set(options.get('sls_states', [])))
# What can I do if a run has multiple states that match?
# In the mean time, find one matching state name and use it.
if matched_states:
tags['state_name'] = sorted(matched_states)[0]
log.debug('Found returned data from %s.', tags['state_name'])
_state_metrics(ret, options, tags) | python | def returner(ret):
'''
Parse the return data and return metrics to AppOptics.
For each state that's provided in the configuration, return tagged metrics for
the result of that state if it's present.
'''
options = _get_options(ret)
states_to_report = ['state.highstate']
if options.get('sls_states'):
states_to_report.append('state.sls')
if ret['fun'] in states_to_report:
tags = options.get('tags', {}).copy()
tags['state_type'] = ret['fun']
log.info("Tags for this run are %s", tags)
matched_states = set(ret['fun_args']).intersection(
set(options.get('sls_states', [])))
# What can I do if a run has multiple states that match?
# In the mean time, find one matching state name and use it.
if matched_states:
tags['state_name'] = sorted(matched_states)[0]
log.debug('Found returned data from %s.', tags['state_name'])
_state_metrics(ret, options, tags) | [
"def",
"returner",
"(",
"ret",
")",
":",
"options",
"=",
"_get_options",
"(",
"ret",
")",
"states_to_report",
"=",
"[",
"'state.highstate'",
"]",
"if",
"options",
".",
"get",
"(",
"'sls_states'",
")",
":",
"states_to_report",
".",
"append",
"(",
"'state.sls'... | Parse the return data and return metrics to AppOptics.
For each state that's provided in the configuration, return tagged metrics for
the result of that state if it's present. | [
"Parse",
"the",
"return",
"data",
"and",
"return",
"metrics",
"to",
"AppOptics",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/appoptics_return.py#L186-L209 | train |
saltstack/salt | salt/states/zabbix_service.py | present | def present(host, service_root, trigger_desc, service_name=None, **kwargs):
'''
.. versionadded:: Fluorine
Ensure service exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split by /)
:param service_name: Name of service
:param trigger_desc: Description of trigger in zabbix
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If services on path does not exists they are created.
.. code-block:: yaml
create_service_icmp:
zabbix_service.present:
- host: server-1
- service_root: Server-group/server icmp
- service_name: server-1-icmp
- trigger_desc: is unavailable by ICMP
'''
if not service_name:
service_name = host
changes_service_added = {host: {'old': 'Service {0} does not exist under {1}.'.format(service_name, service_root),
'new': 'Service {0} added under {1}.'.format(service_name, service_root),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if not host_exists:
ret['comment'] = 'Host {0} does not exists.'.format(host)
return ret
host = __salt__['zabbix.host_get'](name=host, **connection_args)[0]
hostid = host['hostid']
trigger = __salt__['zabbix.triggerid_get'](hostid=hostid, trigger_desc=trigger_desc, **kwargs)
if not trigger:
ret['comment'] = 'Trigger with description: "{0}" does not exists for host {1}.'.format(
trigger_desc, host['name'])
return ret
trigger_id = trigger['result']['triggerid']
root_services = service_root.split('/')
root_id = None
if __opts__['test']:
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = None
ret['comment'] = "Service {0} will be added".format(service_name)
ret['changes'] = changes_service_added
return ret
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if service:
ret['result'] = True
ret['comment'] = "Service {0} already exists".format(service_name)
else:
ret['result'] = None
ret['comment'] = "Service {0} will be added".format(service_name)
ret['changes'] = changes_service_added
return ret
root_id = None
# ensure that root services exists
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
service = __salt__['zabbix.service_add'](service_rootid=root_id, service_name=root_s, **kwargs)
root_id = service['serviceids'][0]
else:
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
service = __salt__['zabbix.service_add'](
service_rootid=root_id, service_name=service_name, triggerid=trigger_id, **kwargs)
if service:
ret['comment'] = "Service {0} added {1} {0} {2}".format(service_name, root_id, trigger_id)
ret['changes'] = changes_service_added
ret['result'] = True
else:
ret['comment'] = "Service {0} could not be added".format(service_name)
ret['result'] = False
else:
ret['comment'] = "Service {0} already exists".format(service_name)
ret['result'] = True
return ret | python | def present(host, service_root, trigger_desc, service_name=None, **kwargs):
'''
.. versionadded:: Fluorine
Ensure service exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split by /)
:param service_name: Name of service
:param trigger_desc: Description of trigger in zabbix
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If services on path does not exists they are created.
.. code-block:: yaml
create_service_icmp:
zabbix_service.present:
- host: server-1
- service_root: Server-group/server icmp
- service_name: server-1-icmp
- trigger_desc: is unavailable by ICMP
'''
if not service_name:
service_name = host
changes_service_added = {host: {'old': 'Service {0} does not exist under {1}.'.format(service_name, service_root),
'new': 'Service {0} added under {1}.'.format(service_name, service_root),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if not host_exists:
ret['comment'] = 'Host {0} does not exists.'.format(host)
return ret
host = __salt__['zabbix.host_get'](name=host, **connection_args)[0]
hostid = host['hostid']
trigger = __salt__['zabbix.triggerid_get'](hostid=hostid, trigger_desc=trigger_desc, **kwargs)
if not trigger:
ret['comment'] = 'Trigger with description: "{0}" does not exists for host {1}.'.format(
trigger_desc, host['name'])
return ret
trigger_id = trigger['result']['triggerid']
root_services = service_root.split('/')
root_id = None
if __opts__['test']:
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = None
ret['comment'] = "Service {0} will be added".format(service_name)
ret['changes'] = changes_service_added
return ret
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if service:
ret['result'] = True
ret['comment'] = "Service {0} already exists".format(service_name)
else:
ret['result'] = None
ret['comment'] = "Service {0} will be added".format(service_name)
ret['changes'] = changes_service_added
return ret
root_id = None
# ensure that root services exists
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
service = __salt__['zabbix.service_add'](service_rootid=root_id, service_name=root_s, **kwargs)
root_id = service['serviceids'][0]
else:
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
service = __salt__['zabbix.service_add'](
service_rootid=root_id, service_name=service_name, triggerid=trigger_id, **kwargs)
if service:
ret['comment'] = "Service {0} added {1} {0} {2}".format(service_name, root_id, trigger_id)
ret['changes'] = changes_service_added
ret['result'] = True
else:
ret['comment'] = "Service {0} could not be added".format(service_name)
ret['result'] = False
else:
ret['comment'] = "Service {0} already exists".format(service_name)
ret['result'] = True
return ret | [
"def",
"present",
"(",
"host",
",",
"service_root",
",",
"trigger_desc",
",",
"service_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"service_name",
":",
"service_name",
"=",
"host",
"changes_service_added",
"=",
"{",
"host",
":",
"{"... | .. versionadded:: Fluorine
Ensure service exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split by /)
:param service_name: Name of service
:param trigger_desc: Description of trigger in zabbix
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If services on path does not exists they are created.
.. code-block:: yaml
create_service_icmp:
zabbix_service.present:
- host: server-1
- service_root: Server-group/server icmp
- service_name: server-1-icmp
- trigger_desc: is unavailable by ICMP | [
"..",
"versionadded",
"::",
"Fluorine"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_service.py#L17-L128 | train |
saltstack/salt | salt/states/zabbix_service.py | absent | def absent(host, service_root, service_name=None, **kwargs):
'''
.. versionadded:: Fluorine
Ensure service does not exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split /)
:param service_name: Name of service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_service_icmp:
zabbix_service.absent:
- host: server-1
- service_root: server-group/server icmp
- service_name: server-1-icmp
'''
if not service_name:
service_name = host
changes_service_deleted = {host: {'old': 'Service {0} exist under {1}.'.format(service_name, service_root),
'new': 'Service {0} deleted under {1}.'.format(service_name, service_root),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if not host_exists:
ret['comment'] = 'Host {0} does not exists.'.format(host)
return ret
root_services = service_root.split('/')
root_id = None
if __opts__['test']:
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = None
ret['comment'] = "Service {0} will be deleted".format(service_name)
ret['changes'] = changes_service_deleted
return ret
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
else:
ret['result'] = None
ret['comment'] = "Service {0} will be deleted".format(service_name)
ret['changes'] = changes_service_deleted
return ret
root_id = None
# ensure that root services exists
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
return ret
else:
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
return ret
else:
service = __salt__['zabbix.service_delete'](service_id=service[0]['serviceid'], **connection_args)
if service:
ret['comment'] = "Service {0} deleted".format(service_name)
ret['changes'] = changes_service_deleted
ret['result'] = True
else:
ret['comment'] = "Service {0} could not be deleted".format(service_name)
ret['result'] = False
return ret | python | def absent(host, service_root, service_name=None, **kwargs):
'''
.. versionadded:: Fluorine
Ensure service does not exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split /)
:param service_name: Name of service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_service_icmp:
zabbix_service.absent:
- host: server-1
- service_root: server-group/server icmp
- service_name: server-1-icmp
'''
if not service_name:
service_name = host
changes_service_deleted = {host: {'old': 'Service {0} exist under {1}.'.format(service_name, service_root),
'new': 'Service {0} deleted under {1}.'.format(service_name, service_root),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if not host_exists:
ret['comment'] = 'Host {0} does not exists.'.format(host)
return ret
root_services = service_root.split('/')
root_id = None
if __opts__['test']:
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = None
ret['comment'] = "Service {0} will be deleted".format(service_name)
ret['changes'] = changes_service_deleted
return ret
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
else:
ret['result'] = None
ret['comment'] = "Service {0} will be deleted".format(service_name)
ret['changes'] = changes_service_deleted
return ret
root_id = None
# ensure that root services exists
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
return ret
else:
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
return ret
else:
service = __salt__['zabbix.service_delete'](service_id=service[0]['serviceid'], **connection_args)
if service:
ret['comment'] = "Service {0} deleted".format(service_name)
ret['changes'] = changes_service_deleted
ret['result'] = True
else:
ret['comment'] = "Service {0} could not be deleted".format(service_name)
ret['result'] = False
return ret | [
"def",
"absent",
"(",
"host",
",",
"service_root",
",",
"service_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"service_name",
":",
"service_name",
"=",
"host",
"changes_service_deleted",
"=",
"{",
"host",
":",
"{",
"'old'",
":",
"'... | .. versionadded:: Fluorine
Ensure service does not exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split /)
:param service_name: Name of service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_service_icmp:
zabbix_service.absent:
- host: server-1
- service_root: server-group/server icmp
- service_name: server-1-icmp | [
"..",
"versionadded",
"::",
"Fluorine",
"Ensure",
"service",
"does",
"not",
"exists",
"under",
"service",
"root",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_service.py#L131-L225 | train |
saltstack/salt | salt/cli/support/intfunc.py | filetree | def filetree(collector, *paths):
'''
Add all files in the tree. If the "path" is a file,
only that file will be added.
:param path: File or directory
:return:
'''
_paths = []
# Unglob
for path in paths:
_paths += glob.glob(path)
for path in set(_paths):
if not path:
out.error('Path not defined', ident=2)
elif not os.path.exists(path):
out.warning('Path {} does not exists'.format(path))
else:
# The filehandler needs to be explicitly passed here, so PyLint needs to accept that.
# pylint: disable=W8470
if os.path.isfile(path):
filename = os.path.basename(path)
try:
file_ref = salt.utils.files.fopen(path) # pylint: disable=W
out.put('Add {}'.format(filename), indent=2)
collector.add(filename)
collector.link(title=path, path=file_ref)
except Exception as err:
out.error(err, ident=4)
# pylint: enable=W8470
else:
try:
for fname in os.listdir(path):
fname = os.path.join(path, fname)
filetree(collector, [fname])
except Exception as err:
out.error(err, ident=4) | python | def filetree(collector, *paths):
'''
Add all files in the tree. If the "path" is a file,
only that file will be added.
:param path: File or directory
:return:
'''
_paths = []
# Unglob
for path in paths:
_paths += glob.glob(path)
for path in set(_paths):
if not path:
out.error('Path not defined', ident=2)
elif not os.path.exists(path):
out.warning('Path {} does not exists'.format(path))
else:
# The filehandler needs to be explicitly passed here, so PyLint needs to accept that.
# pylint: disable=W8470
if os.path.isfile(path):
filename = os.path.basename(path)
try:
file_ref = salt.utils.files.fopen(path) # pylint: disable=W
out.put('Add {}'.format(filename), indent=2)
collector.add(filename)
collector.link(title=path, path=file_ref)
except Exception as err:
out.error(err, ident=4)
# pylint: enable=W8470
else:
try:
for fname in os.listdir(path):
fname = os.path.join(path, fname)
filetree(collector, [fname])
except Exception as err:
out.error(err, ident=4) | [
"def",
"filetree",
"(",
"collector",
",",
"*",
"paths",
")",
":",
"_paths",
"=",
"[",
"]",
"# Unglob",
"for",
"path",
"in",
"paths",
":",
"_paths",
"+=",
"glob",
".",
"glob",
"(",
"path",
")",
"for",
"path",
"in",
"set",
"(",
"_paths",
")",
":",
... | Add all files in the tree. If the "path" is a file,
only that file will be added.
:param path: File or directory
:return: | [
"Add",
"all",
"files",
"in",
"the",
"tree",
".",
"If",
"the",
"path",
"is",
"a",
"file",
"only",
"that",
"file",
"will",
"be",
"added",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/intfunc.py#L17-L53 | train |
saltstack/salt | salt/modules/win_powercfg.py | _get_powercfg_minute_values | def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
out = s
break
else:
out = split[0]
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60} | python | def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
out = s
break
else:
out = split[0]
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60} | [
"def",
"_get_powercfg_minute_values",
"(",
"scheme",
",",
"guid",
",",
"subguid",
",",
"safe_name",
")",
":",
"if",
"scheme",
"is",
"None",
":",
"scheme",
"=",
"_get_current_scheme",
"(",
")",
"if",
"__grains__",
"[",
"'osrelease'",
"]",
"==",
"'7'",
":",
... | Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme | [
"Returns",
"the",
"AC",
"/",
"DC",
"values",
"in",
"an",
"dict",
"for",
"a",
"guid",
"and",
"subguid",
"for",
"a",
"the",
"given",
"scheme"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L44-L69 | train |
saltstack/salt | salt/modules/win_powercfg.py | _set_powercfg_value | def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the AC/DC values of a setting with the given power for the given scheme
'''
if scheme is None:
scheme = _get_current_scheme()
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | python | def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the AC/DC values of a setting with the given power for the given scheme
'''
if scheme is None:
scheme = _get_current_scheme()
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | [
"def",
"_set_powercfg_value",
"(",
"scheme",
",",
"sub_group",
",",
"setting_guid",
",",
"power",
",",
"value",
")",
":",
"if",
"scheme",
"is",
"None",
":",
"scheme",
"=",
"_get_current_scheme",
"(",
")",
"cmd",
"=",
"'powercfg /set{0}valueindex {1} {2} {3} {4}'",... | Sets the AC/DC values of a setting with the given power for the given scheme | [
"Sets",
"the",
"AC",
"/",
"DC",
"values",
"of",
"a",
"setting",
"with",
"the",
"given",
"power",
"for",
"the",
"given",
"scheme"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L72-L81 | train |
saltstack/salt | salt/modules/win_powercfg.py | set_monitor_timeout | def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor 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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout) | python | def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor 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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout) | [
"def",
"set_monitor_timeout",
"(",
"timeout",
",",
"power",
"=",
"'ac'",
",",
"scheme",
"=",
"None",
")",
":",
"return",
"_set_powercfg_value",
"(",
"scheme",
"=",
"scheme",
",",
"sub_group",
"=",
"'SUB_VIDEO'",
",",
"setting_guid",
"=",
"'VIDEOIDLE'",
",",
... | Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor 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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30 | [
"Set",
"the",
"monitor",
"timeout",
"in",
"minutes",
"for",
"the",
"given",
"power",
"scheme"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L84-L123 | train |
saltstack/salt | salt/modules/win_powercfg.py | set_disk_timeout | def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk 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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout) | python | def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk 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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout) | [
"def",
"set_disk_timeout",
"(",
"timeout",
",",
"power",
"=",
"'ac'",
",",
"scheme",
"=",
"None",
")",
":",
"return",
"_set_powercfg_value",
"(",
"scheme",
"=",
"scheme",
",",
"sub_group",
"=",
"'SUB_DISK'",
",",
"setting_guid",
"=",
"'DISKIDLE'",
",",
"powe... | Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk 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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc | [
"Set",
"the",
"disk",
"timeout",
"in",
"minutes",
"for",
"the",
"given",
"power",
"scheme"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L156-L195 | train |
saltstack/salt | salt/modules/win_powercfg.py | set_standby_timeout | def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout) | python | def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout) | [
"def",
"set_standby_timeout",
"(",
"timeout",
",",
"power",
"=",
"'ac'",
",",
"scheme",
"=",
"None",
")",
":",
"return",
"_set_powercfg_value",
"(",
"scheme",
"=",
"scheme",
",",
"sub_group",
"=",
"'SUB_SLEEP'",
",",
"setting_guid",
"=",
"'STANDBYIDLE'",
",",
... | Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc | [
"Set",
"the",
"standby",
"timeout",
"in",
"minutes",
"for",
"the",
"given",
"power",
"scheme"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L228-L267 | train |
saltstack/salt | salt/modules/win_powercfg.py | set_hibernate_timeout | def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout) | python | def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout) | [
"def",
"set_hibernate_timeout",
"(",
"timeout",
",",
"power",
"=",
"'ac'",
",",
"scheme",
"=",
"None",
")",
":",
"return",
"_set_powercfg_value",
"(",
"scheme",
"=",
"scheme",
",",
"sub_group",
"=",
"'SUB_SLEEP'",
",",
"setting_guid",
"=",
"'HIBERNATEIDLE'",
"... | Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
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
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc | [
"Set",
"the",
"hibernate",
"timeout",
"in",
"minutes",
"for",
"the",
"given",
"power",
"scheme"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L299-L338 | train |
saltstack/salt | salt/states/pagerduty_schedule.py | present | def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a pagerduty schedule exists.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/schedules/create.
This means that most arguments are in a dict called "schedule."
User id's can be pagerduty id, or name, or email address.
'''
# for convenience, we accept id, name, or email as the user id.
kwargs['schedule']['name'] = kwargs['name'] # match PD API structure
for schedule_layer in kwargs['schedule']['schedule_layers']:
for user in schedule_layer['users']:
u = __salt__['pagerduty_util.get_resource']('users',
user['user']['id'],
['email', 'name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if u is None:
raise Exception('unknown user: {0}'.format(user))
user['user']['id'] = u['id']
r = __salt__['pagerduty_util.resource_present']('schedules',
['name', 'id'],
_diff,
profile,
subdomain,
api_key,
**kwargs)
return r | python | def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a pagerduty schedule exists.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/schedules/create.
This means that most arguments are in a dict called "schedule."
User id's can be pagerduty id, or name, or email address.
'''
# for convenience, we accept id, name, or email as the user id.
kwargs['schedule']['name'] = kwargs['name'] # match PD API structure
for schedule_layer in kwargs['schedule']['schedule_layers']:
for user in schedule_layer['users']:
u = __salt__['pagerduty_util.get_resource']('users',
user['user']['id'],
['email', 'name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if u is None:
raise Exception('unknown user: {0}'.format(user))
user['user']['id'] = u['id']
r = __salt__['pagerduty_util.resource_present']('schedules',
['name', 'id'],
_diff,
profile,
subdomain,
api_key,
**kwargs)
return r | [
"def",
"present",
"(",
"profile",
"=",
"'pagerduty'",
",",
"subdomain",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# for convenience, we accept id, name, or email as the user id.",
"kwargs",
"[",
"'schedule'",
"]",
"[",
"'name'",... | Ensure that a pagerduty schedule exists.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/schedules/create.
This means that most arguments are in a dict called "schedule."
User id's can be pagerduty id, or name, or email address. | [
"Ensure",
"that",
"a",
"pagerduty",
"schedule",
"exists",
".",
"This",
"method",
"accepts",
"as",
"args",
"everything",
"defined",
"in",
"https",
":",
"//",
"developer",
".",
"pagerduty",
".",
"com",
"/",
"documentation",
"/",
"rest",
"/",
"schedules",
"/",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_schedule.py#L48-L77 | train |
saltstack/salt | salt/states/pagerduty_schedule.py | _diff | def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
state_data['id'] = resource_object['schedule']['id']
objects_differ = None
# first check all the easy top-level properties: everything except the schedule_layers.
for k, v in state_data['schedule'].items():
if k == 'schedule_layers':
continue
if v != resource_object['schedule'][k]:
objects_differ = '{0} {1} {2}'.format(k, v, resource_object['schedule'][k])
break
# check schedule_layers
if not objects_differ:
for layer in state_data['schedule']['schedule_layers']:
# find matching layer name
resource_layer = None
for resource_layer in resource_object['schedule']['schedule_layers']:
found = False
if layer['name'] == resource_layer['name']:
found = True
break
if not found:
objects_differ = 'layer {0} missing'.format(layer['name'])
break
# set the id, so that we will update this layer instead of creating a new one
layer['id'] = resource_layer['id']
# compare contents of layer and resource_layer
for k, v in layer.items():
if k == 'users':
continue
if k == 'start':
continue
if v != resource_layer[k]:
objects_differ = 'layer {0} key {1} {2} != {3}'.format(layer['name'], k, v, resource_layer[k])
break
if objects_differ:
break
# compare layer['users']
if len(layer['users']) != len(resource_layer['users']):
objects_differ = 'num users in layer {0} {1} != {2}'.format(layer['name'], len(layer['users']), len(resource_layer['users']))
break
for user1 in layer['users']:
found = False
user2 = None
for user2 in resource_layer['users']:
# deal with PD API bug: when you submit member_order=N, you get back member_order=N+1
if user1['member_order'] == user2['member_order'] - 1:
found = True
break
if not found:
objects_differ = 'layer {0} no one with member_order {1}'.format(layer['name'], user1['member_order'])
break
if user1['user']['id'] != user2['user']['id']:
objects_differ = 'layer {0} user at member_order {1} {2} != {3}'.format(layer['name'],
user1['member_order'],
user1['user']['id'],
user2['user']['id'])
break
if objects_differ:
return state_data
else:
return {} | python | def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
state_data['id'] = resource_object['schedule']['id']
objects_differ = None
# first check all the easy top-level properties: everything except the schedule_layers.
for k, v in state_data['schedule'].items():
if k == 'schedule_layers':
continue
if v != resource_object['schedule'][k]:
objects_differ = '{0} {1} {2}'.format(k, v, resource_object['schedule'][k])
break
# check schedule_layers
if not objects_differ:
for layer in state_data['schedule']['schedule_layers']:
# find matching layer name
resource_layer = None
for resource_layer in resource_object['schedule']['schedule_layers']:
found = False
if layer['name'] == resource_layer['name']:
found = True
break
if not found:
objects_differ = 'layer {0} missing'.format(layer['name'])
break
# set the id, so that we will update this layer instead of creating a new one
layer['id'] = resource_layer['id']
# compare contents of layer and resource_layer
for k, v in layer.items():
if k == 'users':
continue
if k == 'start':
continue
if v != resource_layer[k]:
objects_differ = 'layer {0} key {1} {2} != {3}'.format(layer['name'], k, v, resource_layer[k])
break
if objects_differ:
break
# compare layer['users']
if len(layer['users']) != len(resource_layer['users']):
objects_differ = 'num users in layer {0} {1} != {2}'.format(layer['name'], len(layer['users']), len(resource_layer['users']))
break
for user1 in layer['users']:
found = False
user2 = None
for user2 in resource_layer['users']:
# deal with PD API bug: when you submit member_order=N, you get back member_order=N+1
if user1['member_order'] == user2['member_order'] - 1:
found = True
break
if not found:
objects_differ = 'layer {0} no one with member_order {1}'.format(layer['name'], user1['member_order'])
break
if user1['user']['id'] != user2['user']['id']:
objects_differ = 'layer {0} user at member_order {1} {2} != {3}'.format(layer['name'],
user1['member_order'],
user1['user']['id'],
user2['user']['id'])
break
if objects_differ:
return state_data
else:
return {} | [
"def",
"_diff",
"(",
"state_data",
",",
"resource_object",
")",
":",
"state_data",
"[",
"'id'",
"]",
"=",
"resource_object",
"[",
"'schedule'",
"]",
"[",
"'id'",
"]",
"objects_differ",
"=",
"None",
"# first check all the easy top-level properties: everything except the ... | helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update. | [
"helper",
"method",
"to",
"compare",
"salt",
"state",
"info",
"with",
"the",
"PagerDuty",
"API",
"json",
"structure",
"and",
"determine",
"if",
"we",
"need",
"to",
"update",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_schedule.py#L94-L163 | train |
saltstack/salt | salt/modules/cron.py | _cron_id | def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid) | python | def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid) | [
"def",
"_cron_id",
"(",
"cron",
")",
":",
"cid",
"=",
"None",
"if",
"cron",
"[",
"'identifier'",
"]",
":",
"cid",
"=",
"cron",
"[",
"'identifier'",
"]",
"else",
":",
"cid",
"=",
"SALT_CRON_NO_IDENTIFIER",
"if",
"cid",
":",
"return",
"_ensure_string",
"("... | SAFETYBELT, Only set if we really have an identifier | [
"SAFETYBELT",
"Only",
"set",
"if",
"we",
"really",
"have",
"an",
"identifier"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L52-L60 | train |
saltstack/salt | salt/modules/cron.py | _cron_matched | def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret | python | def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret | [
"def",
"_cron_matched",
"(",
"cron",
",",
"cmd",
",",
"identifier",
"=",
"None",
")",
":",
"ret",
",",
"id_matched",
"=",
"False",
",",
"None",
"cid",
"=",
"_cron_id",
"(",
"cron",
")",
"if",
"cid",
":",
"if",
"not",
"identifier",
":",
"identifier",
... | Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab | [
"Check",
"if",
":",
"-",
"we",
"find",
"a",
"cron",
"with",
"same",
"cmd",
"old",
"state",
"behavior",
"-",
"but",
"also",
"be",
"smart",
"enough",
"to",
"remove",
"states",
"changed",
"crons",
"where",
"we",
"do",
"not",
"removed",
"priorly",
"by",
"a... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L63-L105 | train |
saltstack/salt | salt/modules/cron.py | _render_tab | def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret | python | def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret | [
"def",
"_render_tab",
"(",
"lst",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"pre",
"in",
"lst",
"[",
"'pre'",
"]",
":",
"ret",
".",
"append",
"(",
"'{0}\\n'",
".",
"format",
"(",
"pre",
")",
")",
"if",
"ret",
":",
"if",
"ret",
"[",
"-",
"1",
"]"... | Takes a tab list structure and renders it to a list for applying it to
a file | [
"Takes",
"a",
"tab",
"list",
"structure",
"and",
"renders",
"it",
"to",
"a",
"list",
"for",
"applying",
"it",
"to",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L119-L177 | train |
saltstack/salt | salt/modules/cron.py | _get_cron_cmdstr | def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path) | python | def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path) | [
"def",
"_get_cron_cmdstr",
"(",
"path",
",",
"user",
"=",
"None",
")",
":",
"if",
"user",
":",
"cmd",
"=",
"'crontab -u {0}'",
".",
"format",
"(",
"user",
")",
"else",
":",
"cmd",
"=",
"'crontab'",
"return",
"'{0} {1}'",
".",
"format",
"(",
"cmd",
",",... | Returns a format string, to be used to build a crontab command. | [
"Returns",
"a",
"format",
"string",
"to",
"be",
"used",
"to",
"build",
"a",
"crontab",
"command",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L180-L188 | train |
saltstack/salt | salt/modules/cron.py | write_cron_file | def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0 | python | def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0 | [
"def",
"write_cron_file",
"(",
"user",
",",
"path",
")",
":",
"if",
"_check_instance_uid_match",
"(",
"user",
")",
"or",
"__grains__",
".",
"get",
"(",
"'os_family'",
")",
"in",
"(",
"'Solaris'",
",",
"'AIX'",
")",
":",
"return",
"__salt__",
"[",
"'cmd.ret... | Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX) | [
"Writes",
"the",
"contents",
"of",
"a",
"file",
"to",
"a",
"user",
"s",
"crontab"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L198-L220 | train |
saltstack/salt | salt/modules/cron.py | _write_cron_lines | def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret | python | def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret | [
"def",
"_write_cron_lines",
"(",
"user",
",",
"lines",
")",
":",
"lines",
"=",
"[",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str",
"(",
"_l",
")",
"for",
"_l",
"in",
"lines",
"]",
"path",
"=",
"salt",
".",
"utils",
".",
"files",
".",
"mks... | Takes a list of lines to be committed to a user's crontab and writes it | [
"Takes",
"a",
"list",
"of",
"lines",
"to",
"be",
"committed",
"to",
"a",
"user",
"s",
"crontab",
"and",
"writes",
"it"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L248-L267 | train |
saltstack/salt | salt/modules/cron.py | _date_time_match | def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')]) | python | def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')]) | [
"def",
"_date_time_match",
"(",
"cron",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"all",
"(",
"[",
"kwargs",
".",
"get",
"(",
"x",
")",
"is",
"None",
"or",
"cron",
"[",
"x",
"]",
"==",
"six",
".",
"text_type",
"(",
"kwargs",
"[",
"x",
"]",
"... | Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab(). | [
"Returns",
"true",
"if",
"the",
"minute",
"hour",
"etc",
".",
"params",
"match",
"their",
"counterparts",
"from",
"the",
"dict",
"returned",
"from",
"list_tab",
"()",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L270-L277 | train |
saltstack/salt | salt/modules/cron.py | raw_cron | def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines) | python | def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines) | [
"def",
"raw_cron",
"(",
"user",
")",
":",
"if",
"_check_instance_uid_match",
"(",
"user",
")",
"or",
"__grains__",
".",
"get",
"(",
"'os_family'",
")",
"in",
"(",
"'Solaris'",
",",
"'AIX'",
")",
":",
"cmd",
"=",
"'crontab -l'",
"# Preserve line endings",
"li... | Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root | [
"Return",
"the",
"contents",
"of",
"the",
"user",
"s",
"crontab"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L280-L312 | train |
saltstack/salt | salt/modules/cron.py | list_tab | def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret | python | def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret | [
"def",
"list_tab",
"(",
"user",
")",
":",
"data",
"=",
"raw_cron",
"(",
"user",
")",
"ret",
"=",
"{",
"'pre'",
":",
"[",
"]",
",",
"'crons'",
":",
"[",
"]",
",",
"'special'",
":",
"[",
"]",
",",
"'env'",
":",
"[",
"]",
"}",
"flag",
"=",
"Fals... | Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root | [
"Return",
"the",
"contents",
"of",
"the",
"specified",
"user",
"s",
"crontab"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L315-L404 | train |
saltstack/salt | salt/modules/cron.py | get_entry | def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False | python | def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False | [
"def",
"get_entry",
"(",
"user",
",",
"identifier",
"=",
"None",
",",
"cmd",
"=",
"None",
")",
":",
"cron_entries",
"=",
"list_tab",
"(",
"user",
")",
".",
"get",
"(",
"'crons'",
",",
"False",
")",
"for",
"cron_entry",
"in",
"cron_entries",
":",
"if",
... | Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1 | [
"Return",
"the",
"specified",
"entry",
"from",
"user",
"s",
"crontab",
".",
"identifier",
"will",
"be",
"used",
"if",
"specified",
"otherwise",
"will",
"lookup",
"cmd",
"Either",
"identifier",
"or",
"cmd",
"should",
"be",
"specified",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L411-L438 | train |
saltstack/salt | salt/modules/cron.py | set_special | def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new' | python | def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new' | [
"def",
"set_special",
"(",
"user",
",",
"special",
",",
"cmd",
",",
"commented",
"=",
"False",
",",
"comment",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
":",
"lst",
"=",
"list_tab",
"(",
"user",
")",
"for",
"cron",
"in",
"lst",
"[",
"'special... | Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar' | [
"Set",
"up",
"a",
"special",
"command",
"in",
"the",
"crontab",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L441-L516 | train |
saltstack/salt | salt/modules/cron.py | _get_cron_date_time | def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret | python | def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret | [
"def",
"_get_cron_date_time",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Define ranges (except daymonth, as it depends on the month)",
"range_max",
"=",
"{",
"'minute'",
":",
"list",
"(",
"list",
"(",
"range",
"(",
"60",
")",
")",
")",
",",
"'hour'",
":",
"list",
"... | Returns a dict of date/time values to be used in a cron entry | [
"Returns",
"a",
"dict",
"of",
"date",
"/",
"time",
"values",
"to",
"be",
"used",
"in",
"a",
"cron",
"entry"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L519-L558 | train |
saltstack/salt | salt/modules/cron.py | set_job | def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new' | python | def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new' | [
"def",
"set_job",
"(",
"user",
",",
"minute",
",",
"hour",
",",
"daymonth",
",",
"month",
",",
"dayweek",
",",
"cmd",
",",
"commented",
"=",
"False",
",",
"comment",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
":",
"# Scrub the types",
"minute",
... | Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly | [
"Sets",
"a",
"cron",
"job",
"up",
"for",
"a",
"specified",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L561-L661 | train |
saltstack/salt | salt/modules/cron.py | rm_special | def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret | python | def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret | [
"def",
"rm_special",
"(",
"user",
",",
"cmd",
",",
"special",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
":",
"lst",
"=",
"list_tab",
"(",
"user",
")",
"ret",
"=",
"'absent'",
"rm_",
"=",
"None",
"for",
"ind",
"in",
"range",
"(",
"len",
"(",... | Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo | [
"Remove",
"a",
"special",
"cron",
"job",
"for",
"a",
"specified",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L664-L694 | train |
saltstack/salt | salt/modules/cron.py | rm_job | def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret | python | def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret | [
"def",
"rm_job",
"(",
"user",
",",
"cmd",
",",
"minute",
"=",
"None",
",",
"hour",
"=",
"None",
",",
"daymonth",
"=",
"None",
",",
"month",
"=",
"None",
",",
"dayweek",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
":",
"lst",
"=",
"list_tab",
... | Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1 | [
"Remove",
"a",
"cron",
"job",
"for",
"a",
"specified",
"user",
".",
"If",
"any",
"of",
"the",
"day",
"/",
"time",
"params",
"are",
"specified",
"the",
"job",
"will",
"only",
"be",
"removed",
"if",
"the",
"specified",
"params",
"match",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L697-L742 | train |
saltstack/salt | salt/modules/cron.py | set_env | def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new' | python | def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new' | [
"def",
"set_env",
"(",
"user",
",",
"name",
",",
"value",
"=",
"None",
")",
":",
"lst",
"=",
"list_tab",
"(",
"user",
")",
"for",
"env",
"in",
"lst",
"[",
"'env'",
"]",
":",
"if",
"name",
"==",
"env",
"[",
"'name'",
"]",
":",
"if",
"value",
"!=... | Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com | [
"Set",
"up",
"an",
"environment",
"variable",
"in",
"the",
"crontab",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L748-L775 | train |
saltstack/salt | salt/modules/cron.py | rm_env | def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret | python | def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret | [
"def",
"rm_env",
"(",
"user",
",",
"name",
")",
":",
"lst",
"=",
"list_tab",
"(",
"user",
")",
"ret",
"=",
"'absent'",
"rm_",
"=",
"None",
"for",
"ind",
"in",
"range",
"(",
"len",
"(",
"lst",
"[",
"'env'",
"]",
")",
")",
":",
"if",
"name",
"=="... | Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO | [
"Remove",
"cron",
"environment",
"variable",
"for",
"a",
"specified",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L778-L801 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | exists | def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err} | python | def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err} | [
"def",
"exists",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
","... | Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket | [
"Given",
"a",
"bucket",
"name",
"check",
"to",
"see",
"if",
"the",
"given",
"bucket",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L103-L127 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | create | def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | python | def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"create",
"(",
"Bucket",
",",
"ACL",
"=",
"None",
",",
"LocationConstraint",
"=",
"None",
",",
"GrantFullControl",
"=",
"None",
",",
"GrantRead",
"=",
"None",
",",
"GrantReadACP",
"=",
"None",
",",
"GrantWrite",
"=",
"None",
",",
"GrantWriteACP",
"=... | Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1 | [
"Given",
"a",
"valid",
"config",
"create",
"an",
"S3",
"Bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L130-L177 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | delete | def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | python | def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete",
"(",
"Bucket",
",",
"MFA",
"=",
"None",
",",
"RequestPayer",
"=",
"None",
",",
"Force",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
"... | Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket | [
"Given",
"a",
"bucket",
"name",
"delete",
"it",
"optionally",
"emptying",
"it",
"first",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L180-L204 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | delete_objects | def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True} | python | def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True} | [
"def",
"delete_objects",
"(",
"Bucket",
",",
"Delete",
",",
"MFA",
"=",
"None",
",",
"RequestPayer",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"isinstance... | Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}' | [
"Delete",
"objects",
"in",
"a",
"given",
"S3",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L207-L249 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | describe | def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)} | python | def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"describe",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
"... | Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket | [
"Given",
"a",
"bucket",
"name",
"describe",
"its",
"properties",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L252-L315 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | empty | def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True} | python | def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True} | [
"def",
"empty",
"(",
"Bucket",
",",
"MFA",
"=",
"None",
",",
"RequestPayer",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"stuff",
"=",
"list_object_versions",
"("... | Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket | [
"Delete",
"all",
"objects",
"in",
"a",
"given",
"S3",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L318-L345 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | list | def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"list",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
... | List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...} | [
"List",
"all",
"buckets",
"owned",
"by",
"the",
"authenticated",
"sender",
"of",
"the",
"request",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L348-L373 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | list_object_versions | def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"list_object_versions",
"(",
"Bucket",
",",
"Delimiter",
"=",
"None",
",",
"EncodingType",
"=",
"None",
",",
"Prefix",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",... | List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket | [
"List",
"objects",
"in",
"a",
"given",
"S3",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L376-L410 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | list_objects | def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"list_objects",
"(",
"Bucket",
",",
"Delimiter",
"=",
"None",
",",
"EncodingType",
"=",
"None",
",",
"Prefix",
"=",
"None",
",",
"FetchOwner",
"=",
"False",
",",
"StartAfter",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
","... | List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket | [
"List",
"objects",
"in",
"a",
"given",
"S3",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L413-L446 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_acl | def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_acl",
"(",
"Bucket",
",",
"ACL",
"=",
"None",
",",
"AccessControlPolicy",
"=",
"None",
",",
"GrantFullControl",
"=",
"None",
",",
"GrantRead",
"=",
"None",
",",
"GrantReadACP",
"=",
"None",
",",
"GrantWrite",
"=",
"None",
",",
"GrantWriteACP",
... | Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"ACL",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L449-L491 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_cors | def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_cors",
"(",
"Bucket",
",",
"CORSRules",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key... | Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]' | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"CORS",
"rules",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L494-L524 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_lifecycle_configuration | def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_lifecycle_configuration",
"(",
"Bucket",
",",
"Rules",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region"... | Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]' | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"Lifecycle",
"rules",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L527-L559 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_logging | def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_logging",
"(",
"Bucket",
",",
"TargetBucket",
"=",
"None",
",",
"TargetPrefix",
"=",
"None",
",",
"TargetGrants",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",... | Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"logging",
"parameters",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L562-L597 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_notification_configuration | def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_notification_configuration",
"(",
"Bucket",
",",
"TopicConfigurations",
"=",
"None",
",",
"QueueConfigurations",
"=",
"None",
",",
"LambdaFunctionConfigurations",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"N... | Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}] | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"notification",
"parameters",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L600-L643 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_policy | def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_policy",
"(",
"Bucket",
",",
"Policy",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key"... | Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...} | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"policy",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L646-L671 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_replication | def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_replication",
"(",
"Bucket",
",",
"Role",
",",
"Rules",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"re... | Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...] | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"replication",
"configuration",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L688-L718 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_request_payment | def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_request_payment",
"(",
"Bucket",
",",
"Payer",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",... | Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"request",
"payment",
"configuration",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L721-L744 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_tagging | def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_tagging",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",... | Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...] | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"tags",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L747-L775 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_versioning | def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_versioning",
"(",
"Bucket",
",",
"Status",
",",
"MFADelete",
"=",
"None",
",",
"MFA",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn"... | Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"versioning",
"configuration",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L778-L807 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | put_website | def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"put_website",
"(",
"Bucket",
",",
"ErrorDocument",
"=",
"None",
",",
"IndexDocument",
"=",
"None",
",",
"RedirectAllRequestsTo",
"=",
"None",
",",
"RoutingRules",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
... | Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}' | [
"Given",
"a",
"valid",
"config",
"update",
"the",
"website",
"configuration",
"for",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L810-L842 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | delete_cors | def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | python | def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_cors",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
... | Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket | [
"Delete",
"the",
"CORS",
"configuration",
"for",
"the",
"given",
"bucket"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L845-L866 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | delete_lifecycle_configuration | def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | python | def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_lifecycle_configuration",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key... | Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket | [
"Delete",
"the",
"lifecycle",
"configuration",
"for",
"the",
"given",
"bucket"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L869-L890 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | delete_replication | def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | python | def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_replication",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket | [
"Delete",
"the",
"replication",
"config",
"from",
"the",
"given",
"bucket"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L917-L938 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | delete_tagging | def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | python | def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_tagging",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key... | Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket | [
"Delete",
"the",
"tags",
"from",
"the",
"given",
"bucket"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L941-L962 | train |
saltstack/salt | salt/modules/boto_s3_bucket.py | delete_website | def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | python | def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_website",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key... | Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket | [
"Remove",
"the",
"website",
"configuration",
"from",
"the",
"given",
"bucket"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L965-L986 | train |
saltstack/salt | salt/acl/__init__.py | PublisherACL.user_is_blacklisted | def user_is_blacklisted(self, user):
'''
Takes a username as a string and returns a boolean. True indicates that
the provided user has been blacklisted
'''
return not salt.utils.stringutils.check_whitelist_blacklist(user, blacklist=self.blacklist.get('users', [])) | python | def user_is_blacklisted(self, user):
'''
Takes a username as a string and returns a boolean. True indicates that
the provided user has been blacklisted
'''
return not salt.utils.stringutils.check_whitelist_blacklist(user, blacklist=self.blacklist.get('users', [])) | [
"def",
"user_is_blacklisted",
"(",
"self",
",",
"user",
")",
":",
"return",
"not",
"salt",
".",
"utils",
".",
"stringutils",
".",
"check_whitelist_blacklist",
"(",
"user",
",",
"blacklist",
"=",
"self",
".",
"blacklist",
".",
"get",
"(",
"'users'",
",",
"[... | Takes a username as a string and returns a boolean. True indicates that
the provided user has been blacklisted | [
"Takes",
"a",
"username",
"as",
"a",
"string",
"and",
"returns",
"a",
"boolean",
".",
"True",
"indicates",
"that",
"the",
"provided",
"user",
"has",
"been",
"blacklisted"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/acl/__init__.py#L29-L34 | train |
saltstack/salt | salt/states/pagerduty_escalation_policy.py | present | def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a pagerduty escalation policy exists. Will create or update as needed.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/escalation_policies/create.
In addition, user and schedule id's will be translated from name (or email address)
into PagerDuty unique ids. For example:
.. code-block:: yaml
pagerduty_escalation_policy.present:
- name: bruce test escalation policy
- escalation_rules:
- targets:
- type: schedule
id: 'bruce test schedule level1'
- type: user
id: 'Bruce Sherrod'
In this example, 'Bruce Sherrod' will be looked up and replaced with the
PagerDuty id (usually a 7 digit all-caps string, e.g. PX6GQL7)
'''
# for convenience, we accept id, name, or email for users
# and we accept the id or name for schedules
for escalation_rule in kwargs['escalation_rules']:
for target in escalation_rule['targets']:
target_id = None
if target['type'] == 'user':
user = __salt__['pagerduty_util.get_resource']('users',
target['id'],
['email', 'name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if user:
target_id = user['id']
elif target['type'] == 'schedule':
schedule = __salt__['pagerduty_util.get_resource']('schedules',
target['id'],
['name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if schedule:
target_id = schedule['schedule']['id']
if target_id is None:
raise Exception('unidentified target: {0}'.format(target))
target['id'] = target_id
r = __salt__['pagerduty_util.resource_present']('escalation_policies',
['name', 'id'],
_diff,
profile,
subdomain,
api_key,
**kwargs)
return r | python | def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a pagerduty escalation policy exists. Will create or update as needed.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/escalation_policies/create.
In addition, user and schedule id's will be translated from name (or email address)
into PagerDuty unique ids. For example:
.. code-block:: yaml
pagerduty_escalation_policy.present:
- name: bruce test escalation policy
- escalation_rules:
- targets:
- type: schedule
id: 'bruce test schedule level1'
- type: user
id: 'Bruce Sherrod'
In this example, 'Bruce Sherrod' will be looked up and replaced with the
PagerDuty id (usually a 7 digit all-caps string, e.g. PX6GQL7)
'''
# for convenience, we accept id, name, or email for users
# and we accept the id or name for schedules
for escalation_rule in kwargs['escalation_rules']:
for target in escalation_rule['targets']:
target_id = None
if target['type'] == 'user':
user = __salt__['pagerduty_util.get_resource']('users',
target['id'],
['email', 'name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if user:
target_id = user['id']
elif target['type'] == 'schedule':
schedule = __salt__['pagerduty_util.get_resource']('schedules',
target['id'],
['name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if schedule:
target_id = schedule['schedule']['id']
if target_id is None:
raise Exception('unidentified target: {0}'.format(target))
target['id'] = target_id
r = __salt__['pagerduty_util.resource_present']('escalation_policies',
['name', 'id'],
_diff,
profile,
subdomain,
api_key,
**kwargs)
return r | [
"def",
"present",
"(",
"profile",
"=",
"'pagerduty'",
",",
"subdomain",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# for convenience, we accept id, name, or email for users",
"# and we accept the id or name for schedules",
"for",
"esca... | Ensure that a pagerduty escalation policy exists. Will create or update as needed.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/escalation_policies/create.
In addition, user and schedule id's will be translated from name (or email address)
into PagerDuty unique ids. For example:
.. code-block:: yaml
pagerduty_escalation_policy.present:
- name: bruce test escalation policy
- escalation_rules:
- targets:
- type: schedule
id: 'bruce test schedule level1'
- type: user
id: 'Bruce Sherrod'
In this example, 'Bruce Sherrod' will be looked up and replaced with the
PagerDuty id (usually a 7 digit all-caps string, e.g. PX6GQL7) | [
"Ensure",
"that",
"a",
"pagerduty",
"escalation",
"policy",
"exists",
".",
"Will",
"create",
"or",
"update",
"as",
"needed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_escalation_policy.py#L49-L107 | train |
saltstack/salt | salt/states/pagerduty_escalation_policy.py | _diff | def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
objects_differ = None
for k, v in state_data.items():
if k == 'escalation_rules':
v = _escalation_rules_to_string(v)
resource_value = _escalation_rules_to_string(resource_object[k])
else:
if k not in resource_object.keys():
objects_differ = True
else:
resource_value = resource_object[k]
if v != resource_value:
objects_differ = '{0} {1} {2}'.format(k, v, resource_value)
break
if objects_differ:
return state_data
else:
return {} | python | def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
objects_differ = None
for k, v in state_data.items():
if k == 'escalation_rules':
v = _escalation_rules_to_string(v)
resource_value = _escalation_rules_to_string(resource_object[k])
else:
if k not in resource_object.keys():
objects_differ = True
else:
resource_value = resource_object[k]
if v != resource_value:
objects_differ = '{0} {1} {2}'.format(k, v, resource_value)
break
if objects_differ:
return state_data
else:
return {} | [
"def",
"_diff",
"(",
"state_data",
",",
"resource_object",
")",
":",
"objects_differ",
"=",
"None",
"for",
"k",
",",
"v",
"in",
"state_data",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'escalation_rules'",
":",
"v",
"=",
"_escalation_rules_to_string",
... | helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update. | [
"helper",
"method",
"to",
"compare",
"salt",
"state",
"info",
"with",
"the",
"PagerDuty",
"API",
"json",
"structure",
"and",
"determine",
"if",
"we",
"need",
"to",
"update",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_escalation_policy.py#L127-L151 | train |
saltstack/salt | salt/states/pagerduty_escalation_policy.py | _escalation_rules_to_string | def _escalation_rules_to_string(escalation_rules):
'convert escalation_rules dict to a string for comparison'
result = ''
for rule in escalation_rules:
result += 'escalation_delay_in_minutes: {0} '.format(rule['escalation_delay_in_minutes'])
for target in rule['targets']:
result += '{0}:{1} '.format(target['type'], target['id'])
return result | python | def _escalation_rules_to_string(escalation_rules):
'convert escalation_rules dict to a string for comparison'
result = ''
for rule in escalation_rules:
result += 'escalation_delay_in_minutes: {0} '.format(rule['escalation_delay_in_minutes'])
for target in rule['targets']:
result += '{0}:{1} '.format(target['type'], target['id'])
return result | [
"def",
"_escalation_rules_to_string",
"(",
"escalation_rules",
")",
":",
"result",
"=",
"''",
"for",
"rule",
"in",
"escalation_rules",
":",
"result",
"+=",
"'escalation_delay_in_minutes: {0} '",
".",
"format",
"(",
"rule",
"[",
"'escalation_delay_in_minutes'",
"]",
")... | convert escalation_rules dict to a string for comparison | [
"convert",
"escalation_rules",
"dict",
"to",
"a",
"string",
"for",
"comparison"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_escalation_policy.py#L154-L161 | train |
saltstack/salt | salt/states/rabbitmq_user.py | _check_perms_changes | def _check_perms_changes(name, newperms, runas=None, existing=None):
'''
Check whether Rabbitmq user's permissions need to be changed.
'''
if not newperms:
return False
if existing is None:
try:
existing = __salt__['rabbitmq.list_user_permissions'](name, runas=runas)
except CommandExecutionError as err:
log.error('Error: %s', err)
return False
perm_need_change = False
for vhost_perms in newperms:
for vhost, perms in six.iteritems(vhost_perms):
if vhost in existing:
existing_vhost = existing[vhost]
if perms != existing_vhost:
# This checks for setting permissions to nothing in the state,
# when previous state runs have already set permissions to
# nothing. We don't want to report a change in this case.
if existing_vhost == '' and perms == ['', '', '']:
continue
perm_need_change = True
else:
perm_need_change = True
return perm_need_change | python | def _check_perms_changes(name, newperms, runas=None, existing=None):
'''
Check whether Rabbitmq user's permissions need to be changed.
'''
if not newperms:
return False
if existing is None:
try:
existing = __salt__['rabbitmq.list_user_permissions'](name, runas=runas)
except CommandExecutionError as err:
log.error('Error: %s', err)
return False
perm_need_change = False
for vhost_perms in newperms:
for vhost, perms in six.iteritems(vhost_perms):
if vhost in existing:
existing_vhost = existing[vhost]
if perms != existing_vhost:
# This checks for setting permissions to nothing in the state,
# when previous state runs have already set permissions to
# nothing. We don't want to report a change in this case.
if existing_vhost == '' and perms == ['', '', '']:
continue
perm_need_change = True
else:
perm_need_change = True
return perm_need_change | [
"def",
"_check_perms_changes",
"(",
"name",
",",
"newperms",
",",
"runas",
"=",
"None",
",",
"existing",
"=",
"None",
")",
":",
"if",
"not",
"newperms",
":",
"return",
"False",
"if",
"existing",
"is",
"None",
":",
"try",
":",
"existing",
"=",
"__salt__",... | Check whether Rabbitmq user's permissions need to be changed. | [
"Check",
"whether",
"Rabbitmq",
"user",
"s",
"permissions",
"need",
"to",
"be",
"changed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_user.py#L44-L73 | train |
saltstack/salt | salt/states/rabbitmq_user.py | _get_current_tags | def _get_current_tags(name, runas=None):
'''
Whether Rabbitmq user's tags need to be changed
'''
try:
return list(__salt__['rabbitmq.list_users'](runas=runas)[name])
except CommandExecutionError as err:
log.error('Error: %s', err)
return [] | python | def _get_current_tags(name, runas=None):
'''
Whether Rabbitmq user's tags need to be changed
'''
try:
return list(__salt__['rabbitmq.list_users'](runas=runas)[name])
except CommandExecutionError as err:
log.error('Error: %s', err)
return [] | [
"def",
"_get_current_tags",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"try",
":",
"return",
"list",
"(",
"__salt__",
"[",
"'rabbitmq.list_users'",
"]",
"(",
"runas",
"=",
"runas",
")",
"[",
"name",
"]",
")",
"except",
"CommandExecutionError",
"as",... | Whether Rabbitmq user's tags need to be changed | [
"Whether",
"Rabbitmq",
"user",
"s",
"tags",
"need",
"to",
"be",
"changed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_user.py#L76-L84 | train |
saltstack/salt | salt/states/rabbitmq_user.py | present | def present(name,
password=None,
force=False,
tags=None,
perms=(),
runas=None):
'''
Ensure the RabbitMQ user exists.
name
User name
password
User's password, if one needs to be set
force
If user exists, forcibly change the password
tags
Optional list of tags for the user
perms
A list of dicts with vhost keys and 3-tuple values
runas
Name of the user to run the command
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
user = __salt__['rabbitmq.user_exists'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
passwd_reqs_update = False
if user and password is not None:
try:
if not __salt__['rabbitmq.check_password'](name,
password, runas=runas):
passwd_reqs_update = True
log.debug('RabbitMQ user %s password update required', name)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
if user and not any((force, perms, tags, passwd_reqs_update)):
log.debug(('RabbitMQ user \'%s\' exists, password is up to'
' date and force is not set.'), name)
ret['comment'] = 'User \'{0}\' is already present.'.format(name)
ret['result'] = True
return ret
if not user:
ret['changes'].update({'user':
{'old': '',
'new': name}})
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be created.'.format(name)
return ret
log.debug(
'RabbitMQ user \'%s\' doesn\'t exist - Creating.', name)
try:
__salt__['rabbitmq.add_user'](name, password, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
else:
log.debug('RabbitMQ user \'%s\' exists', name)
if force or passwd_reqs_update:
if password is not None:
if not __opts__['test']:
try:
__salt__['rabbitmq.change_password'](name, password, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'password':
{'old': '',
'new': 'Set password.'}})
else:
if not __opts__['test']:
log.debug('Password for %s is not set - Clearing password.', name)
try:
__salt__['rabbitmq.clear_password'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'password':
{'old': 'Removed password.',
'new': ''}})
if tags is not None:
current_tags = _get_current_tags(name, runas=runas)
if isinstance(tags, six.string_types):
tags = tags.split()
# Diff the tags sets. Symmetric difference operator ^ will give us
# any element in one set, but not both
if set(tags) ^ set(current_tags):
if not __opts__['test']:
try:
__salt__['rabbitmq.set_user_tags'](name, tags, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'tags':
{'old': current_tags,
'new': tags}})
try:
existing_perms = __salt__['rabbitmq.list_user_permissions'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
if _check_perms_changes(name, perms, runas=runas, existing=existing_perms):
for vhost_perm in perms:
for vhost, perm in six.iteritems(vhost_perm):
if not __opts__['test']:
try:
__salt__['rabbitmq.set_permissions'](
vhost, name, perm[0], perm[1], perm[2], runas=runas
)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
new_perms = {vhost: perm}
if existing_perms != new_perms:
if ret['changes'].get('perms') is None:
ret['changes'].update({'perms':
{'old': {},
'new': {}}})
ret['changes']['perms']['old'].update(existing_perms)
ret['changes']['perms']['new'].update(new_perms)
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = '\'{0}\' is already in the desired state.'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Configuration for \'{0}\' will change.'.format(name)
return ret
ret['comment'] = '\'{0}\' was configured.'.format(name)
return ret | python | def present(name,
password=None,
force=False,
tags=None,
perms=(),
runas=None):
'''
Ensure the RabbitMQ user exists.
name
User name
password
User's password, if one needs to be set
force
If user exists, forcibly change the password
tags
Optional list of tags for the user
perms
A list of dicts with vhost keys and 3-tuple values
runas
Name of the user to run the command
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
user = __salt__['rabbitmq.user_exists'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
passwd_reqs_update = False
if user and password is not None:
try:
if not __salt__['rabbitmq.check_password'](name,
password, runas=runas):
passwd_reqs_update = True
log.debug('RabbitMQ user %s password update required', name)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
if user and not any((force, perms, tags, passwd_reqs_update)):
log.debug(('RabbitMQ user \'%s\' exists, password is up to'
' date and force is not set.'), name)
ret['comment'] = 'User \'{0}\' is already present.'.format(name)
ret['result'] = True
return ret
if not user:
ret['changes'].update({'user':
{'old': '',
'new': name}})
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be created.'.format(name)
return ret
log.debug(
'RabbitMQ user \'%s\' doesn\'t exist - Creating.', name)
try:
__salt__['rabbitmq.add_user'](name, password, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
else:
log.debug('RabbitMQ user \'%s\' exists', name)
if force or passwd_reqs_update:
if password is not None:
if not __opts__['test']:
try:
__salt__['rabbitmq.change_password'](name, password, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'password':
{'old': '',
'new': 'Set password.'}})
else:
if not __opts__['test']:
log.debug('Password for %s is not set - Clearing password.', name)
try:
__salt__['rabbitmq.clear_password'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'password':
{'old': 'Removed password.',
'new': ''}})
if tags is not None:
current_tags = _get_current_tags(name, runas=runas)
if isinstance(tags, six.string_types):
tags = tags.split()
# Diff the tags sets. Symmetric difference operator ^ will give us
# any element in one set, but not both
if set(tags) ^ set(current_tags):
if not __opts__['test']:
try:
__salt__['rabbitmq.set_user_tags'](name, tags, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'tags':
{'old': current_tags,
'new': tags}})
try:
existing_perms = __salt__['rabbitmq.list_user_permissions'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
if _check_perms_changes(name, perms, runas=runas, existing=existing_perms):
for vhost_perm in perms:
for vhost, perm in six.iteritems(vhost_perm):
if not __opts__['test']:
try:
__salt__['rabbitmq.set_permissions'](
vhost, name, perm[0], perm[1], perm[2], runas=runas
)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
new_perms = {vhost: perm}
if existing_perms != new_perms:
if ret['changes'].get('perms') is None:
ret['changes'].update({'perms':
{'old': {},
'new': {}}})
ret['changes']['perms']['old'].update(existing_perms)
ret['changes']['perms']['new'].update(new_perms)
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = '\'{0}\' is already in the desired state.'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Configuration for \'{0}\' will change.'.format(name)
return ret
ret['comment'] = '\'{0}\' was configured.'.format(name)
return ret | [
"def",
"present",
"(",
"name",
",",
"password",
"=",
"None",
",",
"force",
"=",
"False",
",",
"tags",
"=",
"None",
",",
"perms",
"=",
"(",
")",
",",
"runas",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"... | Ensure the RabbitMQ user exists.
name
User name
password
User's password, if one needs to be set
force
If user exists, forcibly change the password
tags
Optional list of tags for the user
perms
A list of dicts with vhost keys and 3-tuple values
runas
Name of the user to run the command | [
"Ensure",
"the",
"RabbitMQ",
"user",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_user.py#L87-L229 | train |
saltstack/salt | salt/states/rabbitmq_user.py | absent | def absent(name,
runas=None):
'''
Ensure the named user is absent
name
The name of the user to remove
runas
User to run the command
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
user_exists = __salt__['rabbitmq.user_exists'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
if user_exists:
if not __opts__['test']:
try:
__salt__['rabbitmq.delete_user'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'name':
{'old': name,
'new': ''}})
else:
ret['result'] = True
ret['comment'] = 'The user \'{0}\' is not present.'.format(name)
return ret
if __opts__['test'] and ret['changes']:
ret['result'] = None
ret['comment'] = 'The user \'{0}\' will be removed.'.format(name)
return ret
ret['result'] = True
ret['comment'] = 'The user \'{0}\' was removed.'.format(name)
return ret | python | def absent(name,
runas=None):
'''
Ensure the named user is absent
name
The name of the user to remove
runas
User to run the command
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
user_exists = __salt__['rabbitmq.user_exists'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
if user_exists:
if not __opts__['test']:
try:
__salt__['rabbitmq.delete_user'](name, runas=runas)
except CommandExecutionError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
ret['changes'].update({'name':
{'old': name,
'new': ''}})
else:
ret['result'] = True
ret['comment'] = 'The user \'{0}\' is not present.'.format(name)
return ret
if __opts__['test'] and ret['changes']:
ret['result'] = None
ret['comment'] = 'The user \'{0}\' will be removed.'.format(name)
return ret
ret['result'] = True
ret['comment'] = 'The user \'{0}\' was removed.'.format(name)
return ret | [
"def",
"absent",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"try",
":",
"user_exists",
"=",
"__salt__",... | Ensure the named user is absent
name
The name of the user to remove
runas
User to run the command | [
"Ensure",
"the",
"named",
"user",
"is",
"absent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_user.py#L232-L272 | train |
saltstack/salt | salt/runners/state.py | pause | def pause(jid, state_id=None, duration=None):
'''
Set up a state id pause, this instructs a running state to pause at a given
state id. This needs to pass in the jid of the running state and can
optionally pass in a duration in seconds.
'''
minion = salt.minion.MasterMinion(__opts__)
minion.functions['state.pause'](jid, state_id, duration) | python | def pause(jid, state_id=None, duration=None):
'''
Set up a state id pause, this instructs a running state to pause at a given
state id. This needs to pass in the jid of the running state and can
optionally pass in a duration in seconds.
'''
minion = salt.minion.MasterMinion(__opts__)
minion.functions['state.pause'](jid, state_id, duration) | [
"def",
"pause",
"(",
"jid",
",",
"state_id",
"=",
"None",
",",
"duration",
"=",
"None",
")",
":",
"minion",
"=",
"salt",
".",
"minion",
".",
"MasterMinion",
"(",
"__opts__",
")",
"minion",
".",
"functions",
"[",
"'state.pause'",
"]",
"(",
"jid",
",",
... | Set up a state id pause, this instructs a running state to pause at a given
state id. This needs to pass in the jid of the running state and can
optionally pass in a duration in seconds. | [
"Set",
"up",
"a",
"state",
"id",
"pause",
"this",
"instructs",
"a",
"running",
"state",
"to",
"pause",
"at",
"a",
"given",
"state",
"id",
".",
"This",
"needs",
"to",
"pass",
"in",
"the",
"jid",
"of",
"the",
"running",
"state",
"and",
"can",
"optionally... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L19-L26 | train |
saltstack/salt | salt/runners/state.py | resume | def resume(jid, state_id=None):
'''
Remove a pause from a jid, allowing it to continue
'''
minion = salt.minion.MasterMinion(__opts__)
minion.functions['state.resume'](jid, state_id) | python | def resume(jid, state_id=None):
'''
Remove a pause from a jid, allowing it to continue
'''
minion = salt.minion.MasterMinion(__opts__)
minion.functions['state.resume'](jid, state_id) | [
"def",
"resume",
"(",
"jid",
",",
"state_id",
"=",
"None",
")",
":",
"minion",
"=",
"salt",
".",
"minion",
".",
"MasterMinion",
"(",
"__opts__",
")",
"minion",
".",
"functions",
"[",
"'state.resume'",
"]",
"(",
"jid",
",",
"state_id",
")"
] | Remove a pause from a jid, allowing it to continue | [
"Remove",
"a",
"pause",
"from",
"a",
"jid",
"allowing",
"it",
"to",
"continue"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L32-L37 | train |
saltstack/salt | salt/runners/state.py | soft_kill | def soft_kill(jid, state_id=None):
'''
Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
at the beginning of the next state run.
'''
minion = salt.minion.MasterMinion(__opts__)
minion.functions['state.soft_kill'](jid, state_id) | python | def soft_kill(jid, state_id=None):
'''
Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
at the beginning of the next state run.
'''
minion = salt.minion.MasterMinion(__opts__)
minion.functions['state.soft_kill'](jid, state_id) | [
"def",
"soft_kill",
"(",
"jid",
",",
"state_id",
"=",
"None",
")",
":",
"minion",
"=",
"salt",
".",
"minion",
".",
"MasterMinion",
"(",
"__opts__",
")",
"minion",
".",
"functions",
"[",
"'state.soft_kill'",
"]",
"(",
"jid",
",",
"state_id",
")"
] | Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
at the beginning of the next state run. | [
"Set",
"up",
"a",
"state",
"run",
"to",
"die",
"before",
"executing",
"the",
"given",
"state",
"id",
"this",
"instructs",
"a",
"running",
"state",
"to",
"safely",
"exit",
"at",
"a",
"given",
"state",
"id",
".",
"This",
"needs",
"to",
"pass",
"in",
"the... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L43-L52 | train |
saltstack/salt | salt/runners/state.py | orchestrate | def orchestrate(mods,
saltenv='base',
test=None,
exclude=None,
pillar=None,
pillarenv=None,
pillar_enc=None,
orchestration_jid=None):
'''
.. versionadded:: 0.17.0
Execute a state run from the master, used as a powerful orchestration
system.
.. seealso:: More Orchestrate documentation
* :ref:`Full Orchestrate Tutorial <orchestrate-runner>`
* :py:mod:`Docs for the master-side state module <salt.states.saltmod>`
CLI Examples:
.. code-block:: bash
salt-run state.orchestrate webserver
salt-run state.orchestrate webserver saltenv=dev test=True
salt-run state.orchestrate webserver saltenv=dev pillarenv=aws
.. versionchanged:: 2014.1.1
Runner renamed from ``state.sls`` to ``state.orchestrate``
.. versionchanged:: 2014.7.0
Runner uses the pillar variable
.. versionchanged:: develop
Runner uses the pillar_enc variable that allows renderers to render the pillar.
This is usable when supplying the contents of a file as pillar, and the file contains
gpg-encrypted entries.
.. seealso:: GPG renderer documentation
CLI Examples:
.. code-block:: bash
salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)"
'''
if pillar is not None and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary'
)
__opts__['file_client'] = 'local'
minion = salt.minion.MasterMinion(__opts__)
if pillarenv is None and 'pillarenv' in __opts__:
pillarenv = __opts__['pillarenv']
if saltenv is None and 'saltenv' in __opts__:
saltenv = __opts__['saltenv']
if orchestration_jid is None:
orchestration_jid = salt.utils.jid.gen_jid(__opts__)
running = minion.functions['state.sls'](
mods,
test,
exclude,
pillar=pillar,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_enc=pillar_enc,
__pub_jid=orchestration_jid,
orchestration_jid=orchestration_jid)
ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'}
res = __utils__['state.check_result'](ret['data'])
if res:
ret['retcode'] = 0
else:
ret['retcode'] = 1
return ret | python | def orchestrate(mods,
saltenv='base',
test=None,
exclude=None,
pillar=None,
pillarenv=None,
pillar_enc=None,
orchestration_jid=None):
'''
.. versionadded:: 0.17.0
Execute a state run from the master, used as a powerful orchestration
system.
.. seealso:: More Orchestrate documentation
* :ref:`Full Orchestrate Tutorial <orchestrate-runner>`
* :py:mod:`Docs for the master-side state module <salt.states.saltmod>`
CLI Examples:
.. code-block:: bash
salt-run state.orchestrate webserver
salt-run state.orchestrate webserver saltenv=dev test=True
salt-run state.orchestrate webserver saltenv=dev pillarenv=aws
.. versionchanged:: 2014.1.1
Runner renamed from ``state.sls`` to ``state.orchestrate``
.. versionchanged:: 2014.7.0
Runner uses the pillar variable
.. versionchanged:: develop
Runner uses the pillar_enc variable that allows renderers to render the pillar.
This is usable when supplying the contents of a file as pillar, and the file contains
gpg-encrypted entries.
.. seealso:: GPG renderer documentation
CLI Examples:
.. code-block:: bash
salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)"
'''
if pillar is not None and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary'
)
__opts__['file_client'] = 'local'
minion = salt.minion.MasterMinion(__opts__)
if pillarenv is None and 'pillarenv' in __opts__:
pillarenv = __opts__['pillarenv']
if saltenv is None and 'saltenv' in __opts__:
saltenv = __opts__['saltenv']
if orchestration_jid is None:
orchestration_jid = salt.utils.jid.gen_jid(__opts__)
running = minion.functions['state.sls'](
mods,
test,
exclude,
pillar=pillar,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_enc=pillar_enc,
__pub_jid=orchestration_jid,
orchestration_jid=orchestration_jid)
ret = {'data': {minion.opts['id']: running}, 'outputter': 'highstate'}
res = __utils__['state.check_result'](ret['data'])
if res:
ret['retcode'] = 0
else:
ret['retcode'] = 1
return ret | [
"def",
"orchestrate",
"(",
"mods",
",",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"pillar",
"=",
"None",
",",
"pillarenv",
"=",
"None",
",",
"pillar_enc",
"=",
"None",
",",
"orchestration_jid",
"=",
"None",
"... | .. versionadded:: 0.17.0
Execute a state run from the master, used as a powerful orchestration
system.
.. seealso:: More Orchestrate documentation
* :ref:`Full Orchestrate Tutorial <orchestrate-runner>`
* :py:mod:`Docs for the master-side state module <salt.states.saltmod>`
CLI Examples:
.. code-block:: bash
salt-run state.orchestrate webserver
salt-run state.orchestrate webserver saltenv=dev test=True
salt-run state.orchestrate webserver saltenv=dev pillarenv=aws
.. versionchanged:: 2014.1.1
Runner renamed from ``state.sls`` to ``state.orchestrate``
.. versionchanged:: 2014.7.0
Runner uses the pillar variable
.. versionchanged:: develop
Runner uses the pillar_enc variable that allows renderers to render the pillar.
This is usable when supplying the contents of a file as pillar, and the file contains
gpg-encrypted entries.
.. seealso:: GPG renderer documentation
CLI Examples:
.. code-block:: bash
salt-run state.orchestrate webserver pillar_enc=gpg pillar="$(cat somefile.json)" | [
"..",
"versionadded",
"::",
"0",
".",
"17",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L55-L135 | train |
saltstack/salt | salt/runners/state.py | orchestrate_single | def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs):
'''
Execute a single state orchestration routine
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run state.orchestrate_single fun=salt.wheel name=key.list_all
'''
if pillar is not None and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary'
)
__opts__['file_client'] = 'local'
minion = salt.minion.MasterMinion(__opts__)
running = minion.functions['state.single'](
fun,
name,
test=None,
queue=False,
pillar=pillar,
**kwargs)
ret = {minion.opts['id']: running}
__jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress')
return ret | python | def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs):
'''
Execute a single state orchestration routine
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run state.orchestrate_single fun=salt.wheel name=key.list_all
'''
if pillar is not None and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary'
)
__opts__['file_client'] = 'local'
minion = salt.minion.MasterMinion(__opts__)
running = minion.functions['state.single'](
fun,
name,
test=None,
queue=False,
pillar=pillar,
**kwargs)
ret = {minion.opts['id']: running}
__jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress')
return ret | [
"def",
"orchestrate_single",
"(",
"fun",
",",
"name",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"pillar",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"pillar",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"pillar",... | Execute a single state orchestration routine
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run state.orchestrate_single fun=salt.wheel name=key.list_all | [
"Execute",
"a",
"single",
"state",
"orchestration",
"routine"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L143-L170 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.