repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/saltutil.py | refresh_pillar | def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret | python | def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret | [
"def",
"refresh_pillar",
"(",
"*",
"*",
"kwargs",
")",
":",
"asynchronous",
"=",
"bool",
"(",
"kwargs",
".",
"get",
"(",
"'async'",
",",
"True",
")",
")",
"try",
":",
"if",
"asynchronous",
":",
"# If we're going to block, first setup a listener",
"ret",
"=",
... | Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False | [
"Signal",
"the",
"minion",
"to",
"refresh",
"the",
"pillar",
"data",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1073-L1104 | train |
saltstack/salt | salt/modules/saltutil.py | is_running | def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret | python | def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret | [
"def",
"is_running",
"(",
"fun",
")",
":",
"run",
"=",
"running",
"(",
")",
"ret",
"=",
"[",
"]",
"for",
"data",
"in",
"run",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"data",
".",
"get",
"(",
"'fun'",
",",
"''",
")",
",",
"fun",
")",
":",
"... | If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate | [
"If",
"the",
"named",
"function",
"is",
"running",
"return",
"the",
"data",
"associated",
"with",
"it",
"/",
"them",
".",
"The",
"argument",
"can",
"be",
"a",
"glob"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1143-L1159 | train |
saltstack/salt | salt/modules/saltutil.py | clear_cache | def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True | python | def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True | [
"def",
"clear_cache",
"(",
"days",
"=",
"-",
"1",
")",
":",
"threshold",
"=",
"time",
".",
"time",
"(",
")",
"-",
"days",
"*",
"24",
"*",
"60",
"*",
"60",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"salt",
".",
"utils",
".",
"files",
".",
... | Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7 | [
"Forcibly",
"removes",
"all",
"caches",
"on",
"a",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1175-L1204 | train |
saltstack/salt | salt/modules/saltutil.py | clear_job_cache | def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True | python | def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True | [
"def",
"clear_job_cache",
"(",
"hours",
"=",
"24",
")",
":",
"threshold",
"=",
"time",
".",
"time",
"(",
")",
"-",
"hours",
"*",
"60",
"*",
"60",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"salt",
".",
"utils",
".",
"files",
".",
"safe_walk",
... | Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12 | [
"Forcibly",
"removes",
"job",
"cache",
"folders",
"and",
"files",
"on",
"a",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1207-L1234 | train |
saltstack/salt | salt/modules/saltutil.py | find_cached_job | def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None | python | def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None | [
"def",
"find_cached_job",
"(",
"jid",
")",
":",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"__opts__",
")",
"proc_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'minion_jobs'",
")",
"job_dir",
... | Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id> | [
"Return",
"the",
"data",
"for",
"a",
"specific",
"cached",
"job",
"id",
".",
"Note",
"this",
"only",
"works",
"if",
"cache_jobs",
"has",
"previously",
"been",
"set",
"to",
"True",
"on",
"the",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1289-L1322 | train |
saltstack/salt | salt/modules/saltutil.py | signal_job | def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return '' | python | def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return '' | [
"def",
"signal_job",
"(",
"jid",
",",
"sig",
")",
":",
"if",
"HAS_PSUTIL",
"is",
"False",
":",
"log",
".",
"warning",
"(",
"'saltutil.signal job called, but psutil is not installed. '",
"'Install psutil to ensure more reliable and accurate PID '",
"'management.'",
")",
"for... | Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15 | [
"Sends",
"a",
"signal",
"to",
"the",
"named",
"salt",
"job",
"s",
"process"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1325-L1360 | train |
saltstack/salt | salt/modules/saltutil.py | term_all_jobs | def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret | python | def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret | [
"def",
"term_all_jobs",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"data",
"in",
"running",
"(",
")",
":",
"ret",
".",
"append",
"(",
"signal_job",
"(",
"data",
"[",
"'jid'",
"]",
",",
"signal",
".",
"SIGTERM",
")",
")",
"return",
"ret"
] | Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs | [
"Sends",
"a",
"termination",
"signal",
"(",
"SIGTERM",
"15",
")",
"to",
"all",
"currently",
"running",
"jobs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1376-L1389 | train |
saltstack/salt | salt/modules/saltutil.py | kill_all_jobs | def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret | python | def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret | [
"def",
"kill_all_jobs",
"(",
")",
":",
"# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to",
"# an appropriate value for the operating system this is running on.",
"ret",
"=",
"[",
"]",
"for",
"data",
"in",
"running",
"(",
")",
":",
"ret",
".",
"appen... | Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs | [
"Sends",
"a",
"kill",
"signal",
"(",
"SIGKILL",
"9",
")",
"to",
"all",
"currently",
"running",
"jobs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1407-L1422 | train |
saltstack/salt | salt/modules/saltutil.py | regen_keys | def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close() | python | def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close() | [
"def",
"regen_keys",
"(",
")",
":",
"for",
"fn_",
"in",
"os",
".",
"listdir",
"(",
"__opts__",
"[",
"'pki_dir'",
"]",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'pki_dir'",
"]",
",",
"fn_",
")",
"try",
":",
"os"... | Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys | [
"Used",
"to",
"regenerate",
"the",
"minion",
"keys",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1425-L1444 | train |
saltstack/salt | salt/modules/saltutil.py | revoke_auth | def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret | python | def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret | [
"def",
"revoke_auth",
"(",
"preserve_minion_cache",
"=",
"False",
")",
":",
"masters",
"=",
"list",
"(",
")",
"ret",
"=",
"True",
"if",
"'master_uri_list'",
"in",
"__opts__",
":",
"for",
"master_uri",
"in",
"__opts__",
"[",
"'master_uri_list'",
"]",
":",
"ma... | The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth | [
"The",
"minion",
"sends",
"a",
"request",
"to",
"the",
"master",
"to",
"revoke",
"its",
"own",
"key",
".",
"Note",
"that",
"the",
"minion",
"session",
"will",
"be",
"revoked",
"and",
"the",
"minion",
"may",
"not",
"be",
"able",
"to",
"return",
"the",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1447-L1483 | train |
saltstack/salt | salt/modules/saltutil.py | cmd | def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret | python | def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret | [
"def",
"cmd",
"(",
"tgt",
",",
"fun",
",",
"arg",
"=",
"(",
")",
",",
"timeout",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"ret",
"=",
"''",
",",
"kwarg",
"=",
"None",
",",
"ssh",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"cfgf... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1537-L1584 | train |
saltstack/salt | salt/modules/saltutil.py | cmd_iter | def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret | python | def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret | [
"def",
"cmd_iter",
"(",
"tgt",
",",
"fun",
",",
"arg",
"=",
"(",
")",
",",
"timeout",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"ret",
"=",
"''",
",",
"kwarg",
"=",
"None",
",",
"ssh",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1587-L1622 | train |
saltstack/salt | salt/modules/saltutil.py | runner | def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return) | python | def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return) | [
"def",
"runner",
"(",
"name",
",",
"arg",
"=",
"None",
",",
"kwarg",
"=",
"None",
",",
"full_return",
"=",
"False",
",",
"saltenv",
"=",
"'base'",
",",
"jid",
"=",
"None",
",",
"asynchronous",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
... | Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}" | [
"Execute",
"a",
"runner",
"function",
".",
"This",
"function",
"must",
"be",
"run",
"on",
"the",
"master",
"either",
"by",
"targeting",
"a",
"minion",
"running",
"on",
"a",
"master",
"or",
"by",
"using",
"salt",
"-",
"call",
"on",
"a",
"master",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1625-L1697 | train |
saltstack/salt | salt/modules/saltutil.py | wheel | def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret | python | def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret | [
"def",
"wheel",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"jid",
"=",
"kwargs",
".",
"pop",
"(",
"'__orchestration_jid__'",
",",
"None",
")",
"saltenv",
"=",
"kwargs",
".",
"pop",
"(",
"'__env__'",
",",
"'base'",
")",
"if",
... | Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data. | [
"Execute",
"a",
"wheel",
"module",
"and",
"function",
".",
"This",
"function",
"must",
"be",
"run",
"against",
"a",
"minion",
"that",
"is",
"local",
"to",
"the",
"master",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1700-L1794 | train |
saltstack/salt | salt/modules/saltutil.py | mmodule | def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs) | python | def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs) | [
"def",
"mmodule",
"(",
"saltenv",
",",
"fun",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mminion",
"=",
"_MMinion",
"(",
"saltenv",
")",
"return",
"mminion",
".",
"functions",
"[",
"fun",
"]",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping | [
"Loads",
"minion",
"modules",
"from",
"an",
"environment",
"so",
"that",
"they",
"can",
"be",
"used",
"in",
"pillars",
"for",
"that",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1830-L1842 | train |
saltstack/salt | salt/modules/zenoss.py | _session | def _session():
'''
Create a session to be used when connecting to Zenoss.
'''
config = __salt__['config.option']('zenoss')
session = requests.session()
session.auth = (config.get('username'), config.get('password'))
session.verify = False
session.headers.update({'Content-type': 'application/json; charset=utf-8'})
return session | python | def _session():
'''
Create a session to be used when connecting to Zenoss.
'''
config = __salt__['config.option']('zenoss')
session = requests.session()
session.auth = (config.get('username'), config.get('password'))
session.verify = False
session.headers.update({'Content-type': 'application/json; charset=utf-8'})
return session | [
"def",
"_session",
"(",
")",
":",
"config",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'zenoss'",
")",
"session",
"=",
"requests",
".",
"session",
"(",
")",
"session",
".",
"auth",
"=",
"(",
"config",
".",
"get",
"(",
"'username'",
")",
",",
... | Create a session to be used when connecting to Zenoss. | [
"Create",
"a",
"session",
"to",
"be",
"used",
"when",
"connecting",
"to",
"Zenoss",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L68-L78 | train |
saltstack/salt | salt/modules/zenoss.py | _router_request | def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps([dict(
action=router,
method=method,
data=data,
type='rpc',
tid=1)])
config = __salt__['config.option']('zenoss')
log.debug('Making request to router %s with method %s', router, method)
url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])
response = _session().post(url, data=req_data)
# The API returns a 200 response code even whe auth is bad.
# With bad auth, the login page is displayed. Here I search for
# an element on the login form to determine if auth failed.
if re.search('name="__ac_name"', response.content):
log.error('Request failed. Bad username/password.')
raise Exception('Request failed. Bad username/password.')
return salt.utils.json.loads(response.content).get('result', None) | python | def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps([dict(
action=router,
method=method,
data=data,
type='rpc',
tid=1)])
config = __salt__['config.option']('zenoss')
log.debug('Making request to router %s with method %s', router, method)
url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])
response = _session().post(url, data=req_data)
# The API returns a 200 response code even whe auth is bad.
# With bad auth, the login page is displayed. Here I search for
# an element on the login form to determine if auth failed.
if re.search('name="__ac_name"', response.content):
log.error('Request failed. Bad username/password.')
raise Exception('Request failed. Bad username/password.')
return salt.utils.json.loads(response.content).get('result', None) | [
"def",
"_router_request",
"(",
"router",
",",
"method",
",",
"data",
"=",
"None",
")",
":",
"if",
"router",
"not",
"in",
"ROUTERS",
":",
"return",
"False",
"req_data",
"=",
"salt",
".",
"utils",
".",
"json",
".",
"dumps",
"(",
"[",
"dict",
"(",
"acti... | Make a request to the Zenoss API router | [
"Make",
"a",
"request",
"to",
"the",
"Zenoss",
"API",
"router"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L81-L107 | train |
saltstack/salt | salt/modules/zenoss.py | find_device | def find_device(device=None):
'''
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device
'''
data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]
all_devices = _router_request('DeviceRouter', 'getDevices', data=data)
for dev in all_devices['devices']:
if dev['name'] == device:
# We need to save the has for later operations
dev['hash'] = all_devices['hash']
log.info('Found device %s in Zenoss', device)
return dev
log.info('Unable to find device %s in Zenoss', device)
return None | python | def find_device(device=None):
'''
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device
'''
data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]
all_devices = _router_request('DeviceRouter', 'getDevices', data=data)
for dev in all_devices['devices']:
if dev['name'] == device:
# We need to save the has for later operations
dev['hash'] = all_devices['hash']
log.info('Found device %s in Zenoss', device)
return dev
log.info('Unable to find device %s in Zenoss', device)
return None | [
"def",
"find_device",
"(",
"device",
"=",
"None",
")",
":",
"data",
"=",
"[",
"{",
"'uid'",
":",
"'/zport/dmd/Devices'",
",",
"'params'",
":",
"{",
"}",
",",
"'limit'",
":",
"None",
"}",
"]",
"all_devices",
"=",
"_router_request",
"(",
"'DeviceRouter'",
... | Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device | [
"Find",
"a",
"device",
"in",
"Zenoss",
".",
"If",
"device",
"not",
"found",
"returns",
"None",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L118-L139 | train |
saltstack/salt | salt/modules/zenoss.py | add_device | def add_device(device=None, device_class=None, collector='localhost', prod_state=1000):
'''
A function to connect to a zenoss server and add a new device entry.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default.
device_class: (Optional) The device class to use. If none, will determine based on kernel grain.
collector: (Optional) The collector to use for this device. Defaults to 'localhost'.
prod_state: (Optional) The prodState to set on the device. If none, defaults to 1000 ( production )
CLI Example:
salt '*' zenoss.add_device
'''
if not device:
device = __salt__['grains.get']('fqdn')
if not device_class:
device_class = _determine_device_class()
log.info('Adding device %s to zenoss', device)
data = dict(deviceName=device, deviceClass=device_class, model=True, collector=collector, productionState=prod_state)
response = _router_request('DeviceRouter', 'addDevice', data=[data])
return response | python | def add_device(device=None, device_class=None, collector='localhost', prod_state=1000):
'''
A function to connect to a zenoss server and add a new device entry.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default.
device_class: (Optional) The device class to use. If none, will determine based on kernel grain.
collector: (Optional) The collector to use for this device. Defaults to 'localhost'.
prod_state: (Optional) The prodState to set on the device. If none, defaults to 1000 ( production )
CLI Example:
salt '*' zenoss.add_device
'''
if not device:
device = __salt__['grains.get']('fqdn')
if not device_class:
device_class = _determine_device_class()
log.info('Adding device %s to zenoss', device)
data = dict(deviceName=device, deviceClass=device_class, model=True, collector=collector, productionState=prod_state)
response = _router_request('DeviceRouter', 'addDevice', data=[data])
return response | [
"def",
"add_device",
"(",
"device",
"=",
"None",
",",
"device_class",
"=",
"None",
",",
"collector",
"=",
"'localhost'",
",",
"prod_state",
"=",
"1000",
")",
":",
"if",
"not",
"device",
":",
"device",
"=",
"__salt__",
"[",
"'grains.get'",
"]",
"(",
"'fqd... | A function to connect to a zenoss server and add a new device entry.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default.
device_class: (Optional) The device class to use. If none, will determine based on kernel grain.
collector: (Optional) The collector to use for this device. Defaults to 'localhost'.
prod_state: (Optional) The prodState to set on the device. If none, defaults to 1000 ( production )
CLI Example:
salt '*' zenoss.add_device | [
"A",
"function",
"to",
"connect",
"to",
"a",
"zenoss",
"server",
"and",
"add",
"a",
"new",
"device",
"entry",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L161-L183 | train |
saltstack/salt | salt/modules/zenoss.py | set_prod_state | def set_prod_state(prod_state, device=None):
'''
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname
'''
if not device:
device = __salt__['grains.get']('fqdn')
device_object = find_device(device)
if not device_object:
return "Unable to find a device in Zenoss for {0}".format(device)
log.info('Setting prodState to %d on %s device', prod_state, device)
data = dict(uids=[device_object['uid']], prodState=prod_state, hashcheck=device_object['hash'])
return _router_request('DeviceRouter', 'setProductionState', [data]) | python | def set_prod_state(prod_state, device=None):
'''
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname
'''
if not device:
device = __salt__['grains.get']('fqdn')
device_object = find_device(device)
if not device_object:
return "Unable to find a device in Zenoss for {0}".format(device)
log.info('Setting prodState to %d on %s device', prod_state, device)
data = dict(uids=[device_object['uid']], prodState=prod_state, hashcheck=device_object['hash'])
return _router_request('DeviceRouter', 'setProductionState', [data]) | [
"def",
"set_prod_state",
"(",
"prod_state",
",",
"device",
"=",
"None",
")",
":",
"if",
"not",
"device",
":",
"device",
"=",
"__salt__",
"[",
"'grains.get'",
"]",
"(",
"'fqdn'",
")",
"device_object",
"=",
"find_device",
"(",
"device",
")",
"if",
"not",
"... | A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname | [
"A",
"function",
"to",
"set",
"the",
"prod_state",
"in",
"zenoss",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L186-L208 | train |
saltstack/salt | salt/modules/restartcheck.py | _valid_deleted_file | def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret | python | def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret | [
"def",
"_valid_deleted_file",
"(",
"path",
")",
":",
"ret",
"=",
"False",
"if",
"path",
".",
"endswith",
"(",
"' (deleted)'",
")",
":",
"ret",
"=",
"True",
"if",
"re",
".",
"compile",
"(",
"r\"\\(path inode=[0-9]+\\)$\"",
")",
".",
"search",
"(",
"path",
... | Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file | [
"Filters",
"file",
"path",
"against",
"unwanted",
"directories",
"and",
"decides",
"whether",
"file",
"is",
"marked",
"as",
"deleted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L93-L112 | train |
saltstack/salt | salt/modules/restartcheck.py | _deleted_files | def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass | python | def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass | [
"def",
"_deleted_files",
"(",
")",
":",
"deleted_files",
"=",
"[",
"]",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
":",
"# pylint: disable=too-many-nested-blocks",
"try",
":",
"pinfo",
"=",
"proc",
".",
"as_dict",
"(",
"attrs",
"=",
"[",
... | Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure. | [
"Iterates",
"over",
"/",
"proc",
"/",
"PID",
"/",
"maps",
"and",
"/",
"proc",
"/",
"PID",
"/",
"fd",
"links",
"and",
"returns",
"list",
"of",
"desired",
"deleted",
"files",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L115-L182 | train |
saltstack/salt | salt/modules/restartcheck.py | _format_output | def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret | python | def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret | [
"def",
"_format_output",
"(",
"kernel_restart",
",",
"packages",
",",
"verbose",
",",
"restartable",
",",
"nonrestartable",
",",
"restartservicecommands",
",",
"restartinitcommands",
")",
":",
"if",
"not",
"verbose",
":",
"packages",
"=",
"restartable",
"+",
"nonr... | Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts | [
"Formats",
"the",
"output",
"of",
"the",
"restartcheck",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L185-L240 | train |
saltstack/salt | salt/modules/restartcheck.py | _kernel_versions_debian | def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions | python | def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions | [
"def",
"_kernel_versions_debian",
"(",
")",
":",
"kernel_get_selections",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'dpkg --get-selections linux-image-*'",
")",
"kernels",
"=",
"[",
"]",
"kernel_versions",
"=",
"[",
"]",
"for",
"line",
"in",
"kernel_get_selectio... | Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command. | [
"Last",
"installed",
"kernel",
"name",
"for",
"Debian",
"based",
"systems",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L243-L278 | train |
saltstack/salt | salt/modules/restartcheck.py | _kernel_versions_redhat | def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions | python | def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions | [
"def",
"_kernel_versions_redhat",
"(",
")",
":",
"kernel_get_last",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'rpm -q --last kernel'",
")",
"kernels",
"=",
"[",
"]",
"kernel_versions",
"=",
"[",
"]",
"for",
"line",
"in",
"kernel_get_last",
".",
"splitlines",... | Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command. | [
"Name",
"of",
"the",
"last",
"installed",
"kernel",
"for",
"Red",
"Hat",
"based",
"systems",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L281-L299 | train |
saltstack/salt | salt/modules/restartcheck.py | _kernel_versions_nilrt | def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver] | python | def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver] | [
"def",
"_kernel_versions_nilrt",
"(",
")",
":",
"kver",
"=",
"None",
"def",
"_get_kver_from_bin",
"(",
"kbin",
")",
":",
"'''\n Get kernel version from a binary image or None if detection fails\n '''",
"kvregex",
"=",
"r'[0-9]+\\.[0-9]+\\.[0-9]+-rt\\S+'",
"kernel_st... | Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command. | [
"Last",
"installed",
"kernel",
"name",
"for",
"Debian",
"based",
"systems",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L302-L345 | train |
saltstack/salt | salt/modules/restartcheck.py | _check_timeout | def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.') | python | def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.') | [
"def",
"_check_timeout",
"(",
"start_time",
",",
"timeout",
")",
":",
"timeout_milisec",
"=",
"timeout",
"*",
"60000",
"if",
"timeout_milisec",
"<",
"(",
"int",
"(",
"round",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
")",
"-",
"start_time",
... | Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command. | [
"Name",
"of",
"the",
"last",
"installed",
"kernel",
"for",
"Red",
"Hat",
"based",
"systems",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L348-L357 | train |
saltstack/salt | salt/modules/restartcheck.py | _file_changed_nilrt | def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet")) | python | def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet")) | [
"def",
"_file_changed_nilrt",
"(",
"full_filepath",
")",
":",
"rs_state_dir",
"=",
"\"/var/lib/salt/restartcheck_state\"",
"base_filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"full_filepath",
")",
"timestamp_file",
"=",
"os",
".",
"path",
".",
"join",
"... | Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched | [
"Detect",
"whether",
"a",
"file",
"changed",
"in",
"an",
"NILinuxRT",
"system",
"using",
"md5sum",
"and",
"timestamp",
"files",
"from",
"a",
"state",
"directory",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L360-L384 | train |
saltstack/salt | salt/modules/restartcheck.py | _sysapi_changed_nilrt | def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False | python | def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False | [
"def",
"_sysapi_changed_nilrt",
"(",
")",
":",
"nisysapi_path",
"=",
"'/usr/local/natinst/share/nisysapi.ini'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"nisysapi_path",
")",
"and",
"_file_changed_nilrt",
"(",
"nisysapi_path",
")",
":",
"return",
"True",
"restar... | Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist | [
"Besides",
"the",
"normal",
"Linux",
"kernel",
"driver",
"interfaces",
"NILinuxRT",
"-",
"supported",
"hardware",
"features",
"an",
"extensible",
"plugin",
"-",
"based",
"device",
"enumeration",
"and",
"configuration",
"interface",
"named",
"System",
"API",
".",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L402-L438 | train |
saltstack/salt | salt/modules/restartcheck.py | restartcheck | def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret | python | def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret | [
"def",
"restartcheck",
"(",
"ignorelist",
"=",
"None",
",",
"blacklist",
"=",
"None",
",",
"excludepid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
"... | Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck | [
"Analyzes",
"files",
"openeded",
"by",
"running",
"processes",
"and",
"seeks",
"for",
"packages",
"which",
"need",
"to",
"be",
"restarted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L442-L645 | train |
saltstack/salt | salt/states/pbm.py | default_vsan_policy_configured | def default_vsan_policy_configured(name, policy):
'''
Configures the default VSAN policy on a vCenter.
The state assumes there is only one default VSAN policy on a vCenter.
policy
Dict representation of a policy
'''
# TODO Refactor when recurse_differ supports list_differ
# It's going to make the whole thing much easier
policy_copy = copy.deepcopy(policy)
proxy_type = __salt__['vsphere.get_proxy_type']()
log.trace('proxy_type = %s', proxy_type)
# All allowed proxies have a shim execution module with the same
# name which implementes a get_details function
# All allowed proxies have a vcenter detail
vcenter = __salt__['{0}.get_details'.format(proxy_type)]()['vcenter']
log.info('Running %s on vCenter \'%s\'', name, vcenter)
log.trace('policy = %s', policy)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
si = None
try:
#TODO policy schema validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_policy = __salt__['vsphere.list_default_vsan_policy'](si)
log.trace('current_policy = %s', current_policy)
# Building all diffs between the current and expected policy
# XXX We simplify the comparison by assuming we have at most 1
# sub_profile
if policy.get('subprofiles'):
if len(policy['subprofiles']) > 1:
raise ArgumentValueError('Multiple sub_profiles ({0}) are not '
'supported in the input policy')
subprofile = policy['subprofiles'][0]
current_subprofile = current_policy['subprofiles'][0]
capabilities_differ = list_diff(current_subprofile['capabilities'],
subprofile.get('capabilities', []),
key='id')
del policy['subprofiles']
if subprofile.get('capabilities'):
del subprofile['capabilities']
del current_subprofile['capabilities']
# Get the subprofile diffs without the capability keys
subprofile_differ = recursive_diff(current_subprofile,
dict(subprofile))
del current_policy['subprofiles']
policy_differ = recursive_diff(current_policy, policy)
if policy_differ.diffs or capabilities_differ.diffs or \
subprofile_differ.diffs:
if 'name' in policy_differ.new_values or \
'description' in policy_differ.new_values:
raise ArgumentValueError(
'\'name\' and \'description\' of the default VSAN policy '
'cannot be updated')
changes_required = True
if __opts__['test']:
str_changes = []
if policy_differ.diffs:
str_changes.extend([change for change in
policy_differ.changes_str.split('\n')])
if subprofile_differ.diffs or capabilities_differ.diffs:
str_changes.append('subprofiles:')
if subprofile_differ.diffs:
str_changes.extend(
[' {0}'.format(change) for change in
subprofile_differ.changes_str.split('\n')])
if capabilities_differ.diffs:
str_changes.append(' capabilities:')
str_changes.extend(
[' {0}'.format(change) for change in
capabilities_differ.changes_str2.split('\n')])
comments.append(
'State {0} will update the default VSAN policy on '
'vCenter \'{1}\':\n{2}'
''.format(name, vcenter, '\n'.join(str_changes)))
else:
__salt__['vsphere.update_storage_policy'](
policy=current_policy['name'],
policy_dict=policy_copy,
service_instance=si)
comments.append('Updated the default VSAN policy in vCenter '
'\'{0}\''.format(vcenter))
log.info(comments[-1])
new_values = policy_differ.new_values
new_values['subprofiles'] = [subprofile_differ.new_values]
new_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.new_values
if not new_values['subprofiles'][0]['capabilities']:
del new_values['subprofiles'][0]['capabilities']
if not new_values['subprofiles'][0]:
del new_values['subprofiles']
old_values = policy_differ.old_values
old_values['subprofiles'] = [subprofile_differ.old_values]
old_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.old_values
if not old_values['subprofiles'][0]['capabilities']:
del old_values['subprofiles'][0]['capabilities']
if not old_values['subprofiles'][0]:
del old_values['subprofiles']
changes.update({'default_vsan_policy':
{'new': new_values,
'old': old_values}})
log.trace(changes)
__salt__['vsphere.disconnect'](si)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Default VSAN policy in vCenter '
'\'{0}\' is correctly configured. '
'Nothing to be done.'.format(vcenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret | python | def default_vsan_policy_configured(name, policy):
'''
Configures the default VSAN policy on a vCenter.
The state assumes there is only one default VSAN policy on a vCenter.
policy
Dict representation of a policy
'''
# TODO Refactor when recurse_differ supports list_differ
# It's going to make the whole thing much easier
policy_copy = copy.deepcopy(policy)
proxy_type = __salt__['vsphere.get_proxy_type']()
log.trace('proxy_type = %s', proxy_type)
# All allowed proxies have a shim execution module with the same
# name which implementes a get_details function
# All allowed proxies have a vcenter detail
vcenter = __salt__['{0}.get_details'.format(proxy_type)]()['vcenter']
log.info('Running %s on vCenter \'%s\'', name, vcenter)
log.trace('policy = %s', policy)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
si = None
try:
#TODO policy schema validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_policy = __salt__['vsphere.list_default_vsan_policy'](si)
log.trace('current_policy = %s', current_policy)
# Building all diffs between the current and expected policy
# XXX We simplify the comparison by assuming we have at most 1
# sub_profile
if policy.get('subprofiles'):
if len(policy['subprofiles']) > 1:
raise ArgumentValueError('Multiple sub_profiles ({0}) are not '
'supported in the input policy')
subprofile = policy['subprofiles'][0]
current_subprofile = current_policy['subprofiles'][0]
capabilities_differ = list_diff(current_subprofile['capabilities'],
subprofile.get('capabilities', []),
key='id')
del policy['subprofiles']
if subprofile.get('capabilities'):
del subprofile['capabilities']
del current_subprofile['capabilities']
# Get the subprofile diffs without the capability keys
subprofile_differ = recursive_diff(current_subprofile,
dict(subprofile))
del current_policy['subprofiles']
policy_differ = recursive_diff(current_policy, policy)
if policy_differ.diffs or capabilities_differ.diffs or \
subprofile_differ.diffs:
if 'name' in policy_differ.new_values or \
'description' in policy_differ.new_values:
raise ArgumentValueError(
'\'name\' and \'description\' of the default VSAN policy '
'cannot be updated')
changes_required = True
if __opts__['test']:
str_changes = []
if policy_differ.diffs:
str_changes.extend([change for change in
policy_differ.changes_str.split('\n')])
if subprofile_differ.diffs or capabilities_differ.diffs:
str_changes.append('subprofiles:')
if subprofile_differ.diffs:
str_changes.extend(
[' {0}'.format(change) for change in
subprofile_differ.changes_str.split('\n')])
if capabilities_differ.diffs:
str_changes.append(' capabilities:')
str_changes.extend(
[' {0}'.format(change) for change in
capabilities_differ.changes_str2.split('\n')])
comments.append(
'State {0} will update the default VSAN policy on '
'vCenter \'{1}\':\n{2}'
''.format(name, vcenter, '\n'.join(str_changes)))
else:
__salt__['vsphere.update_storage_policy'](
policy=current_policy['name'],
policy_dict=policy_copy,
service_instance=si)
comments.append('Updated the default VSAN policy in vCenter '
'\'{0}\''.format(vcenter))
log.info(comments[-1])
new_values = policy_differ.new_values
new_values['subprofiles'] = [subprofile_differ.new_values]
new_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.new_values
if not new_values['subprofiles'][0]['capabilities']:
del new_values['subprofiles'][0]['capabilities']
if not new_values['subprofiles'][0]:
del new_values['subprofiles']
old_values = policy_differ.old_values
old_values['subprofiles'] = [subprofile_differ.old_values]
old_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.old_values
if not old_values['subprofiles'][0]['capabilities']:
del old_values['subprofiles'][0]['capabilities']
if not old_values['subprofiles'][0]:
del old_values['subprofiles']
changes.update({'default_vsan_policy':
{'new': new_values,
'old': old_values}})
log.trace(changes)
__salt__['vsphere.disconnect'](si)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Default VSAN policy in vCenter '
'\'{0}\' is correctly configured. '
'Nothing to be done.'.format(vcenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret | [
"def",
"default_vsan_policy_configured",
"(",
"name",
",",
"policy",
")",
":",
"# TODO Refactor when recurse_differ supports list_differ",
"# It's going to make the whole thing much easier",
"policy_copy",
"=",
"copy",
".",
"deepcopy",
"(",
"policy",
")",
"proxy_type",
"=",
"... | Configures the default VSAN policy on a vCenter.
The state assumes there is only one default VSAN policy on a vCenter.
policy
Dict representation of a policy | [
"Configures",
"the",
"default",
"VSAN",
"policy",
"on",
"a",
"vCenter",
".",
"The",
"state",
"assumes",
"there",
"is",
"only",
"one",
"default",
"VSAN",
"policy",
"on",
"a",
"vCenter",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pbm.py#L138-L275 | train |
saltstack/salt | salt/states/pbm.py | default_storage_policy_assigned | def default_storage_policy_assigned(name, policy, datastore):
'''
Assigns a default storage policy to a datastore
policy
Name of storage policy
datastore
Name of datastore
'''
log.info('Running state %s for policy \'%s\', datastore \'%s\'.',
name, policy, datastore)
changes = {}
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
si = None
try:
si = __salt__['vsphere.get_service_instance_via_proxy']()
existing_policy = \
__salt__['vsphere.list_default_storage_policy_of_datastore'](
datastore=datastore, service_instance=si)
if existing_policy['name'] == policy:
comment = ('Storage policy \'{0}\' is already assigned to '
'datastore \'{1}\'. Nothing to be done.'
''.format(policy, datastore))
else:
changes_required = True
changes = {
'default_storage_policy': {'old': existing_policy['name'],
'new': policy}}
if __opts__['test']:
comment = ('State {0} will assign storage policy \'{1}\' to '
'datastore \'{2}\'.').format(name, policy,
datastore)
else:
__salt__['vsphere.assign_default_storage_policy_to_datastore'](
policy=policy, datastore=datastore, service_instance=si)
comment = ('Storage policy \'{0} was assigned to datastore '
'\'{1}\'.').format(policy, name)
log.info(comment)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
ret['comment'] = comment
if changes_required:
ret.update({
'changes': changes,
'result': None if __opts__['test'] else True,
})
else:
ret['result'] = True
return ret | python | def default_storage_policy_assigned(name, policy, datastore):
'''
Assigns a default storage policy to a datastore
policy
Name of storage policy
datastore
Name of datastore
'''
log.info('Running state %s for policy \'%s\', datastore \'%s\'.',
name, policy, datastore)
changes = {}
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
si = None
try:
si = __salt__['vsphere.get_service_instance_via_proxy']()
existing_policy = \
__salt__['vsphere.list_default_storage_policy_of_datastore'](
datastore=datastore, service_instance=si)
if existing_policy['name'] == policy:
comment = ('Storage policy \'{0}\' is already assigned to '
'datastore \'{1}\'. Nothing to be done.'
''.format(policy, datastore))
else:
changes_required = True
changes = {
'default_storage_policy': {'old': existing_policy['name'],
'new': policy}}
if __opts__['test']:
comment = ('State {0} will assign storage policy \'{1}\' to '
'datastore \'{2}\'.').format(name, policy,
datastore)
else:
__salt__['vsphere.assign_default_storage_policy_to_datastore'](
policy=policy, datastore=datastore, service_instance=si)
comment = ('Storage policy \'{0} was assigned to datastore '
'\'{1}\'.').format(policy, name)
log.info(comment)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
ret['comment'] = comment
if changes_required:
ret.update({
'changes': changes,
'result': None if __opts__['test'] else True,
})
else:
ret['result'] = True
return ret | [
"def",
"default_storage_policy_assigned",
"(",
"name",
",",
"policy",
",",
"datastore",
")",
":",
"log",
".",
"info",
"(",
"'Running state %s for policy \\'%s\\', datastore \\'%s\\'.'",
",",
"name",
",",
"policy",
",",
"datastore",
")",
"changes",
"=",
"{",
"}",
"... | Assigns a default storage policy to a datastore
policy
Name of storage policy
datastore
Name of datastore | [
"Assigns",
"a",
"default",
"storage",
"policy",
"to",
"a",
"datastore"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pbm.py#L441-L500 | train |
saltstack/salt | salt/modules/cloud.py | _get_client | def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client | python | def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client | [
"def",
"_get_client",
"(",
")",
":",
"client",
"=",
"salt",
".",
"cloud",
".",
"CloudClient",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__opts__",
"[",
"'conf_file'",
"]",
")",
",",
"'cloud'",
")",
",",
"pil... | Return a cloud client | [
"Return",
"a",
"cloud",
"client"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L41-L49 | train |
saltstack/salt | salt/modules/cloud.py | has_instance | def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True | python | def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True | [
"def",
"has_instance",
"(",
"name",
",",
"provider",
"=",
"None",
")",
":",
"data",
"=",
"get_instance",
"(",
"name",
",",
"provider",
")",
"if",
"data",
"is",
"None",
":",
"return",
"False",
"return",
"True"
] | Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance | [
"Return",
"true",
"if",
"the",
"instance",
"is",
"found",
"on",
"a",
"provider"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L140-L153 | train |
saltstack/salt | salt/modules/cloud.py | get_instance | def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info | python | def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info | [
"def",
"get_instance",
"(",
"name",
",",
"provider",
"=",
"None",
")",
":",
"data",
"=",
"action",
"(",
"fun",
"=",
"'show_instance'",
",",
"names",
"=",
"[",
"name",
"]",
",",
"provider",
"=",
"provider",
")",
"info",
"=",
"salt",
".",
"utils",
".",... | Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }} | [
"Return",
"details",
"on",
"an",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L156-L183 | train |
saltstack/salt | salt/modules/cloud.py | profile_ | def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info | python | def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info | [
"def",
"profile_",
"(",
"profile",
",",
"names",
",",
"vm_overrides",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"if",
"isinstance",
"(",
"opts",
",",
"dict",
")",
":",
"client",
... | Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance | [
"Spin",
"up",
"an",
"instance",
"using",
"Salt",
"Cloud"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L186-L200 | train |
saltstack/salt | salt/modules/cloud.py | map_run | def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info | python | def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info | [
"def",
"map_run",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"info",
"=",
"client",
".",
"map_run",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
"return",
"info"
] | Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>' | [
"Execute",
"a",
"salt",
"cloud",
"map",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L203-L229 | train |
saltstack/salt | salt/modules/cloud.py | action | def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info | python | def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info | [
"def",
"action",
"(",
"fun",
"=",
"None",
",",
"cloudmap",
"=",
"None",
",",
"names",
"=",
"None",
",",
"provider",
"=",
"None",
",",
"instance",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"try",
":",
... | Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f | [
"Execute",
"a",
"single",
"action",
"on",
"the",
"given",
"provider",
"/",
"instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L247-L272 | train |
saltstack/salt | salt/modules/cloud.py | create | def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info | python | def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info | [
"def",
"create",
"(",
"provider",
",",
"names",
",",
"opts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"if",
"isinstance",
"(",
"opts",
",",
"dict",
")",
":",
"client",
".",
"opts",
".",
"update",
"(",
... | Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True | [
"Create",
"an",
"instance",
"using",
"Salt",
"Cloud"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L275-L289 | train |
saltstack/salt | salt/modules/cloud.py | volume_list | def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name'] | python | def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name'] | [
"def",
"volume_list",
"(",
"provider",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"info",
"=",
"client",
".",
"extra_action",
"(",
"action",
"=",
"'volume_list'",
",",
"provider",
"=",
"provider",
",",
"names",
"=",
"'name'",
")",
"return",
"info",
... | List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova | [
"List",
"block",
"storage",
"volumes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L292-L305 | train |
saltstack/salt | salt/modules/cloud.py | volume_attach | def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info | python | def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info | [
"def",
"volume_attach",
"(",
"provider",
",",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"info",
"=",
"client",
".",
"extra_action",
"(",
"provider",
"=",
"provider",
",",
"names",
"=",
"names",
",",
"action",
"... | Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf' | [
"Attach",
"volume",
"to",
"a",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L340-L353 | train |
saltstack/salt | salt/modules/cloud.py | network_list | def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names') | python | def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names') | [
"def",
"network_list",
"(",
"provider",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"return",
"client",
".",
"extra_action",
"(",
"action",
"=",
"'network_list'",
",",
"provider",
"=",
"provider",
",",
"names",
"=",
"'names'",
")"
] | List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova | [
"List",
"private",
"networks"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L372-L384 | train |
saltstack/salt | salt/modules/cloud.py | network_create | def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs) | python | def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs) | [
"def",
"network_create",
"(",
"provider",
",",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"return",
"client",
".",
"extra_action",
"(",
"provider",
"=",
"provider",
",",
"names",
"=",
"names",
",",
"action",
"=",
... | Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24' | [
"Create",
"private",
"network"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L387-L399 | train |
saltstack/salt | salt/modules/cloud.py | virtual_interface_list | def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs) | python | def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs) | [
"def",
"virtual_interface_list",
"(",
"provider",
",",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"return",
"client",
".",
"extra_action",
"(",
"provider",
"=",
"provider",
",",
"names",
"=",
"names",
",",
"action",... | List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master'] | [
"List",
"virtual",
"interfaces",
"on",
"a",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L402-L414 | train |
saltstack/salt | salt/modules/cloud.py | virtual_interface_create | def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs) | python | def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs) | [
"def",
"virtual_interface_create",
"(",
"provider",
",",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"return",
"client",
".",
"extra_action",
"(",
"provider",
"=",
"provider",
",",
"names",
"=",
"names",
",",
"action... | Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt' | [
"Attach",
"private",
"interfaces",
"to",
"a",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L417-L429 | train |
saltstack/salt | salt/modules/netbsd_sysctl.py | show | def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'kern',
'vm',
'vfs',
'net',
'hw',
'machdep',
'user',
'ddb',
'proc',
'emul',
'security',
'init'
)
cmd = 'sysctl -ae'
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
comps = ['']
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = re.split('[=:]', line, 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret | python | def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'kern',
'vm',
'vfs',
'net',
'hw',
'machdep',
'user',
'ddb',
'proc',
'emul',
'security',
'init'
)
cmd = 'sysctl -ae'
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
comps = ['']
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = re.split('[=:]', line, 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret | [
"def",
"show",
"(",
"config_file",
"=",
"False",
")",
":",
"roots",
"=",
"(",
"'kern'",
",",
"'vm'",
",",
"'vfs'",
",",
"'net'",
",",
"'hw'",
",",
"'machdep'",
",",
"'user'",
",",
"'ddb'",
",",
"'proc'",
",",
"'emul'",
",",
"'security'",
",",
"'init'... | Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show | [
"Return",
"a",
"list",
"of",
"sysctl",
"parameters",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsd_sysctl.py#L30-L66 | train |
saltstack/salt | salt/modules/netbsd_sysctl.py | get | def get(name):
'''
Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem
'''
cmd = 'sysctl -n {0}'.format(name)
out = __salt__['cmd.run'](cmd, python_shell=False)
return out | python | def get(name):
'''
Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem
'''
cmd = 'sysctl -n {0}'.format(name)
out = __salt__['cmd.run'](cmd, python_shell=False)
return out | [
"def",
"get",
"(",
"name",
")",
":",
"cmd",
"=",
"'sysctl -n {0}'",
".",
"format",
"(",
"name",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"return",
"out"
] | Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem | [
"Return",
"a",
"single",
"sysctl",
"parameter",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsd_sysctl.py#L69-L81 | train |
saltstack/salt | salt/modules/netbsd_sysctl.py | persist | def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
'''
nlines = []
edited = False
value = six.text_type(value)
# create /etc/sysctl.conf if not present
if not os.path.isfile(config):
try:
with salt.utils.files.fopen(config, 'w+'):
pass
except (IOError, OSError):
msg = 'Could not create {0}'
raise CommandExecutionError(msg.format(config))
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
m = re.match(r'{0}(\??=)'.format(name), line)
if not m:
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = '{0}{1}{2}{3}'.format(name, m.group(1), value, rest)
nlines.append(new_line)
edited = True
if not edited:
newline = '{0}={1}'.format(name, value)
nlines.append("{0}\n".format(newline))
with salt.utils.files.fopen(config, 'wb') as ofile:
ofile.writelines(
salt.utils.data.encode(nlines)
)
assign(name, value)
return 'Updated' | python | def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
'''
nlines = []
edited = False
value = six.text_type(value)
# create /etc/sysctl.conf if not present
if not os.path.isfile(config):
try:
with salt.utils.files.fopen(config, 'w+'):
pass
except (IOError, OSError):
msg = 'Could not create {0}'
raise CommandExecutionError(msg.format(config))
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
m = re.match(r'{0}(\??=)'.format(name), line)
if not m:
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = '{0}{1}{2}{3}'.format(name, m.group(1), value, rest)
nlines.append(new_line)
edited = True
if not edited:
newline = '{0}={1}'.format(name, value)
nlines.append("{0}\n".format(newline))
with salt.utils.files.fopen(config, 'wb') as ofile:
ofile.writelines(
salt.utils.data.encode(nlines)
)
assign(name, value)
return 'Updated' | [
"def",
"persist",
"(",
"name",
",",
"value",
",",
"config",
"=",
"'/etc/sysctl.conf'",
")",
":",
"nlines",
"=",
"[",
"]",
"edited",
"=",
"False",
"value",
"=",
"six",
".",
"text_type",
"(",
"value",
")",
"# create /etc/sysctl.conf if not present",
"if",
"not... | Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50 | [
"Assign",
"and",
"persist",
"a",
"simple",
"sysctl",
"parameter",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsd_sysctl.py#L106-L162 | train |
saltstack/salt | salt/states/pushover.py | post_message | def post_message(name,
user=None,
device=None,
message=None,
title=None,
priority=None,
expire=None,
retry=None,
sound=None,
api_version=1,
token=None):
'''
Send a message to a PushOver channel.
.. code-block:: yaml
pushover-message:
pushover.post_message:
- user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- title: Salt Returner
- device: phone
- priority: -1
- expire: 3600
- retry: 5
The following parameters are required:
name
The unique name for this event.
user
The user or group of users to send the message to. Must be ID of user, not name
or email address.
message
The message that is to be sent to the PushOver channel.
The following parameters are optional:
title
The title to use for the message.
device
The device for the user to send the message to.
priority
The priority for the message.
expire
The message should expire after specified amount of seconds.
retry
The message should be resent this many times.
token
The token for PushOver to use for authentication,
if not specified in the configuration options of master or minion.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'The following message is to be sent to PushOver: {0}'.format(message)
ret['result'] = None
return ret
if not user:
ret['comment'] = 'PushOver user is missing: {0}'.format(user)
return ret
if not message:
ret['comment'] = 'PushOver message is missing: {0}'.format(message)
return ret
result = __salt__['pushover.post_message'](
user=user,
message=message,
title=title,
device=device,
priority=priority,
expire=expire,
retry=retry,
token=token,
)
if result:
ret['result'] = True
ret['comment'] = 'Sent message: {0}'.format(name)
else:
ret['comment'] = 'Failed to send message: {0}'.format(name)
return ret | python | def post_message(name,
user=None,
device=None,
message=None,
title=None,
priority=None,
expire=None,
retry=None,
sound=None,
api_version=1,
token=None):
'''
Send a message to a PushOver channel.
.. code-block:: yaml
pushover-message:
pushover.post_message:
- user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- title: Salt Returner
- device: phone
- priority: -1
- expire: 3600
- retry: 5
The following parameters are required:
name
The unique name for this event.
user
The user or group of users to send the message to. Must be ID of user, not name
or email address.
message
The message that is to be sent to the PushOver channel.
The following parameters are optional:
title
The title to use for the message.
device
The device for the user to send the message to.
priority
The priority for the message.
expire
The message should expire after specified amount of seconds.
retry
The message should be resent this many times.
token
The token for PushOver to use for authentication,
if not specified in the configuration options of master or minion.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'The following message is to be sent to PushOver: {0}'.format(message)
ret['result'] = None
return ret
if not user:
ret['comment'] = 'PushOver user is missing: {0}'.format(user)
return ret
if not message:
ret['comment'] = 'PushOver message is missing: {0}'.format(message)
return ret
result = __salt__['pushover.post_message'](
user=user,
message=message,
title=title,
device=device,
priority=priority,
expire=expire,
retry=retry,
token=token,
)
if result:
ret['result'] = True
ret['comment'] = 'Sent message: {0}'.format(name)
else:
ret['comment'] = 'Failed to send message: {0}'.format(name)
return ret | [
"def",
"post_message",
"(",
"name",
",",
"user",
"=",
"None",
",",
"device",
"=",
"None",
",",
"message",
"=",
"None",
",",
"title",
"=",
"None",
",",
"priority",
"=",
"None",
",",
"expire",
"=",
"None",
",",
"retry",
"=",
"None",
",",
"sound",
"="... | Send a message to a PushOver channel.
.. code-block:: yaml
pushover-message:
pushover.post_message:
- user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- title: Salt Returner
- device: phone
- priority: -1
- expire: 3600
- retry: 5
The following parameters are required:
name
The unique name for this event.
user
The user or group of users to send the message to. Must be ID of user, not name
or email address.
message
The message that is to be sent to the PushOver channel.
The following parameters are optional:
title
The title to use for the message.
device
The device for the user to send the message to.
priority
The priority for the message.
expire
The message should expire after specified amount of seconds.
retry
The message should be resent this many times.
token
The token for PushOver to use for authentication,
if not specified in the configuration options of master or minion. | [
"Send",
"a",
"message",
"to",
"a",
"PushOver",
"channel",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pushover.py#L42-L137 | train |
saltstack/salt | salt/modules/dig.py | check_ip | def check_ip(addr):
'''
Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
'''
try:
addr = addr.rsplit('/', 1)
except AttributeError:
# Non-string passed
return False
if salt.utils.network.is_ipv4(addr[0]):
try:
if 1 <= int(addr[1]) <= 32:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
if salt.utils.network.is_ipv6(addr[0]):
try:
if 8 <= int(addr[1]) <= 128:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
return False | python | def check_ip(addr):
'''
Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
'''
try:
addr = addr.rsplit('/', 1)
except AttributeError:
# Non-string passed
return False
if salt.utils.network.is_ipv4(addr[0]):
try:
if 1 <= int(addr[1]) <= 32:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
if salt.utils.network.is_ipv6(addr[0]):
try:
if 8 <= int(addr[1]) <= 128:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
return False | [
"def",
"check_ip",
"(",
"addr",
")",
":",
"try",
":",
"addr",
"=",
"addr",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"except",
"AttributeError",
":",
"# Non-string passed",
"return",
"False",
"if",
"salt",
".",
"utils",
".",
"network",
".",
"is_ipv4",
... | Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888 | [
"Check",
"if",
"address",
"is",
"a",
"valid",
"IP",
".",
"returns",
"True",
"if",
"valid",
"otherwise",
"False",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L32-L72 | train |
saltstack/salt | salt/modules/dig.py | AAAA | def AAAA(host, nameserver=None):
'''
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'AAAA']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)] | python | def AAAA(host, nameserver=None):
'''
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'AAAA']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)] | [
"def",
"AAAA",
"(",
"host",
",",
"nameserver",
"=",
"None",
")",
":",
"dig",
"=",
"[",
"'dig'",
",",
"'+short'",
",",
"six",
".",
"text_type",
"(",
"host",
")",
",",
"'AAAA'",
"]",
"if",
"nameserver",
"is",
"not",
"None",
":",
"dig",
".",
"append",... | Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com | [
"Return",
"the",
"AAAA",
"record",
"for",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L105-L132 | train |
saltstack/salt | salt/modules/dig.py | NS | def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'NS']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
if resolve:
ret = []
for ns_host in cmd['stdout'].split('\n'):
for ip_addr in A(ns_host, nameserver):
ret.append(ip_addr)
return ret
return cmd['stdout'].split('\n') | python | def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'NS']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
if resolve:
ret = []
for ns_host in cmd['stdout'].split('\n'):
for ip_addr in A(ns_host, nameserver):
ret.append(ip_addr)
return ret
return cmd['stdout'].split('\n') | [
"def",
"NS",
"(",
"domain",
",",
"resolve",
"=",
"True",
",",
"nameserver",
"=",
"None",
")",
":",
"dig",
"=",
"[",
"'dig'",
",",
"'+short'",
",",
"six",
".",
"text_type",
"(",
"domain",
")",
",",
"'NS'",
"]",
"if",
"nameserver",
"is",
"not",
"None... | Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com | [
"Return",
"a",
"list",
"of",
"IPs",
"of",
"the",
"nameservers",
"for",
"domain"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L135-L168 | train |
saltstack/salt | salt/modules/dig.py | SPF | def SPF(domain, record='SPF', nameserver=None):
'''
Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com
'''
spf_re = re.compile(r'(?:\+|~)?(ip[46]|include):(.+)')
cmd = ['dig', '+short', six.text_type(domain), record]
if nameserver is not None:
cmd.append('@{0}'.format(nameserver))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
# In this case, 0 is not the same as False
if result['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
result['retcode']
)
return []
if result['stdout'] == '' and record == 'SPF':
# empty string is successful query, but nothing to return. So, try TXT
# record.
return SPF(domain, 'TXT', nameserver)
sections = re.sub('"', '', result['stdout']).split()
if not sections or sections[0] != 'v=spf1':
return []
if sections[1].startswith('redirect='):
# Run a lookup on the part after 'redirect=' (9 chars)
return SPF(sections[1][9:], 'SPF', nameserver)
ret = []
for section in sections[1:]:
try:
mechanism, address = spf_re.match(section).groups()
except AttributeError:
# Regex was not matched
continue
if mechanism == 'include':
ret.extend(SPF(address, 'SPF', nameserver))
elif mechanism in ('ip4', 'ip6') and check_ip(address):
ret.append(address)
return ret | python | def SPF(domain, record='SPF', nameserver=None):
'''
Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com
'''
spf_re = re.compile(r'(?:\+|~)?(ip[46]|include):(.+)')
cmd = ['dig', '+short', six.text_type(domain), record]
if nameserver is not None:
cmd.append('@{0}'.format(nameserver))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
# In this case, 0 is not the same as False
if result['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
result['retcode']
)
return []
if result['stdout'] == '' and record == 'SPF':
# empty string is successful query, but nothing to return. So, try TXT
# record.
return SPF(domain, 'TXT', nameserver)
sections = re.sub('"', '', result['stdout']).split()
if not sections or sections[0] != 'v=spf1':
return []
if sections[1].startswith('redirect='):
# Run a lookup on the part after 'redirect=' (9 chars)
return SPF(sections[1][9:], 'SPF', nameserver)
ret = []
for section in sections[1:]:
try:
mechanism, address = spf_re.match(section).groups()
except AttributeError:
# Regex was not matched
continue
if mechanism == 'include':
ret.extend(SPF(address, 'SPF', nameserver))
elif mechanism in ('ip4', 'ip6') and check_ip(address):
ret.append(address)
return ret | [
"def",
"SPF",
"(",
"domain",
",",
"record",
"=",
"'SPF'",
",",
"nameserver",
"=",
"None",
")",
":",
"spf_re",
"=",
"re",
".",
"compile",
"(",
"r'(?:\\+|~)?(ip[46]|include):(.+)'",
")",
"cmd",
"=",
"[",
"'dig'",
",",
"'+short'",
",",
"six",
".",
"text_typ... | Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com | [
"Return",
"the",
"allowed",
"IPv4",
"ranges",
"in",
"the",
"SPF",
"record",
"for",
"domain",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L171-L223 | train |
saltstack/salt | salt/modules/dig.py | MX | def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'MX']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
stdout = [x.split() for x in cmd['stdout'].split('\n')]
if resolve:
return [
(lambda x: [x[0], A(x[1], nameserver)[0]])(x) for x in stdout
]
return stdout | python | def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'MX']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
stdout = [x.split() for x in cmd['stdout'].split('\n')]
if resolve:
return [
(lambda x: [x[0], A(x[1], nameserver)[0]])(x) for x in stdout
]
return stdout | [
"def",
"MX",
"(",
"domain",
",",
"resolve",
"=",
"False",
",",
"nameserver",
"=",
"None",
")",
":",
"dig",
"=",
"[",
"'dig'",
",",
"'+short'",
",",
"six",
".",
"text_type",
"(",
"domain",
")",
",",
"'MX'",
"]",
"if",
"nameserver",
"is",
"not",
"Non... | Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com | [
"Return",
"a",
"list",
"of",
"lists",
"for",
"the",
"MX",
"of",
"domain",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L226-L264 | train |
saltstack/salt | salt/modules/dig.py | TXT | def TXT(host, nameserver=None):
'''
Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com
'''
dig = ['dig', '+short', six.text_type(host), 'TXT']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
return [i for i in cmd['stdout'].split('\n')] | python | def TXT(host, nameserver=None):
'''
Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com
'''
dig = ['dig', '+short', six.text_type(host), 'TXT']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
return [i for i in cmd['stdout'].split('\n')] | [
"def",
"TXT",
"(",
"host",
",",
"nameserver",
"=",
"None",
")",
":",
"dig",
"=",
"[",
"'dig'",
",",
"'+short'",
",",
"six",
".",
"text_type",
"(",
"host",
")",
",",
"'TXT'",
"]",
"if",
"nameserver",
"is",
"not",
"None",
":",
"dig",
".",
"append",
... | Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com | [
"Return",
"the",
"TXT",
"record",
"for",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L267-L293 | train |
saltstack/salt | salt/modules/freebsd_sysctl.py | show | def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'compat',
'debug',
'dev',
'hptmv',
'hw',
'kern',
'machdep',
'net',
'p1003_1b',
'security',
'user',
'vfs',
'vm'
)
cmd = 'sysctl -ae'
ret = {}
comps = ['']
if config_file:
# If the file doesn't exist, return an empty list
if not os.path.exists(config_file):
return []
try:
with salt.utils.files.fopen(config_file, 'r') as f:
for line in f.readlines():
l = line.strip()
if l != "" and not l.startswith("#"):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
return ret
except (OSError, IOError):
log.error('Could not open sysctl config file')
return None
else:
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret | python | def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'compat',
'debug',
'dev',
'hptmv',
'hw',
'kern',
'machdep',
'net',
'p1003_1b',
'security',
'user',
'vfs',
'vm'
)
cmd = 'sysctl -ae'
ret = {}
comps = ['']
if config_file:
# If the file doesn't exist, return an empty list
if not os.path.exists(config_file):
return []
try:
with salt.utils.files.fopen(config_file, 'r') as f:
for line in f.readlines():
l = line.strip()
if l != "" and not l.startswith("#"):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
return ret
except (OSError, IOError):
log.error('Could not open sysctl config file')
return None
else:
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret | [
"def",
"show",
"(",
"config_file",
"=",
"False",
")",
":",
"roots",
"=",
"(",
"'compat'",
",",
"'debug'",
",",
"'dev'",
",",
"'hptmv'",
",",
"'hw'",
",",
"'kern'",
",",
"'machdep'",
",",
"'net'",
",",
"'p1003_1b'",
",",
"'security'",
",",
"'user'",
","... | Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show | [
"Return",
"a",
"list",
"of",
"sysctl",
"parameters",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_sysctl.py#L40-L95 | train |
saltstack/salt | salt/modules/freebsd_sysctl.py | assign | def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50
'''
ret = {}
cmd = 'sysctl {0}="{1}"'.format(name, value)
data = __salt__['cmd.run_all'](cmd, python_shell=False)
if data['retcode'] != 0:
raise CommandExecutionError('sysctl failed: {0}'.format(
data['stderr']))
new_name, new_value = data['stdout'].split(':', 1)
ret[new_name] = new_value.split(' -> ')[-1]
return ret | python | def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50
'''
ret = {}
cmd = 'sysctl {0}="{1}"'.format(name, value)
data = __salt__['cmd.run_all'](cmd, python_shell=False)
if data['retcode'] != 0:
raise CommandExecutionError('sysctl failed: {0}'.format(
data['stderr']))
new_name, new_value = data['stdout'].split(':', 1)
ret[new_name] = new_value.split(' -> ')[-1]
return ret | [
"def",
"assign",
"(",
"name",
",",
"value",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'sysctl {0}=\"{1}\"'",
".",
"format",
"(",
"name",
",",
"value",
")",
"data",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"... | Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50 | [
"Assign",
"a",
"single",
"sysctl",
"parameter",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_sysctl.py#L113-L132 | train |
saltstack/salt | salt/modules/freebsd_sysctl.py | persist | def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf
'''
nlines = []
edited = False
value = six.text_type(value)
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line).rstrip('\n')
if not line.startswith('{0}='.format(name)):
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = _formatfor(key, value, config, rest)
nlines.append(new_line)
edited = True
if not edited:
nlines.append("{0}\n".format(_formatfor(name, value, config)))
with salt.utils.files.fopen(config, 'w+') as ofile:
nlines = [salt.utils.stringutils.to_str(_l) + '\n' for _l in nlines]
ofile.writelines(nlines)
if config != '/boot/loader.conf':
assign(name, value)
return 'Updated' | python | def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf
'''
nlines = []
edited = False
value = six.text_type(value)
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line).rstrip('\n')
if not line.startswith('{0}='.format(name)):
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = _formatfor(key, value, config, rest)
nlines.append(new_line)
edited = True
if not edited:
nlines.append("{0}\n".format(_formatfor(name, value, config)))
with salt.utils.files.fopen(config, 'w+') as ofile:
nlines = [salt.utils.stringutils.to_str(_l) + '\n' for _l in nlines]
ofile.writelines(nlines)
if config != '/boot/loader.conf':
assign(name, value)
return 'Updated' | [
"def",
"persist",
"(",
"name",
",",
"value",
",",
"config",
"=",
"'/etc/sysctl.conf'",
")",
":",
"nlines",
"=",
"[",
"]",
"edited",
"=",
"False",
"value",
"=",
"six",
".",
"text_type",
"(",
"value",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".... | Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf | [
"Assign",
"and",
"persist",
"a",
"simple",
"sysctl",
"parameter",
"for",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_sysctl.py#L135-L177 | train |
saltstack/salt | salt/states/augeas.py | _workout_filename | def _workout_filename(filename):
'''
Recursively workout the file name from an augeas change
'''
if os.path.isfile(filename) or filename == '/':
if filename == '/':
filename = None
return filename
else:
return _workout_filename(os.path.dirname(filename)) | python | def _workout_filename(filename):
'''
Recursively workout the file name from an augeas change
'''
if os.path.isfile(filename) or filename == '/':
if filename == '/':
filename = None
return filename
else:
return _workout_filename(os.path.dirname(filename)) | [
"def",
"_workout_filename",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
"or",
"filename",
"==",
"'/'",
":",
"if",
"filename",
"==",
"'/'",
":",
"filename",
"=",
"None",
"return",
"filename",
"else",
":",
"re... | Recursively workout the file name from an augeas change | [
"Recursively",
"workout",
"the",
"file",
"name",
"from",
"an",
"augeas",
"change"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/augeas.py#L53-L62 | train |
saltstack/salt | salt/states/augeas.py | _check_filepath | def _check_filepath(changes):
'''
Ensure all changes are fully qualified and affect only one file.
This ensures that the diff output works and a state change is not
incorrectly reported.
'''
filename = None
for change_ in changes:
try:
cmd, arg = change_.split(' ', 1)
if cmd not in METHOD_MAP:
error = 'Command {0} is not supported (yet)'.format(cmd)
raise ValueError(error)
method = METHOD_MAP[cmd]
parts = salt.utils.args.shlex_split(arg)
if method in ['set', 'setm', 'move', 'remove']:
filename_ = parts[0]
else:
_, _, filename_ = parts
if not filename_.startswith('/files'):
error = 'Changes should be prefixed with ' \
'/files if no context is provided,' \
' change: {0}'.format(change_)
raise ValueError(error)
filename_ = re.sub('^/files|/$', '', filename_)
if filename is not None:
if filename != filename_:
error = 'Changes should be made to one ' \
'file at a time, detected changes ' \
'to {0} and {1}'.format(filename, filename_)
raise ValueError(error)
filename = filename_
except (ValueError, IndexError) as err:
log.error(err)
if 'error' not in locals():
error = 'Invalid formatted command, ' \
'see debug log for details: {0}' \
.format(change_)
else:
error = six.text_type(err)
raise ValueError(error)
filename = _workout_filename(filename)
return filename | python | def _check_filepath(changes):
'''
Ensure all changes are fully qualified and affect only one file.
This ensures that the diff output works and a state change is not
incorrectly reported.
'''
filename = None
for change_ in changes:
try:
cmd, arg = change_.split(' ', 1)
if cmd not in METHOD_MAP:
error = 'Command {0} is not supported (yet)'.format(cmd)
raise ValueError(error)
method = METHOD_MAP[cmd]
parts = salt.utils.args.shlex_split(arg)
if method in ['set', 'setm', 'move', 'remove']:
filename_ = parts[0]
else:
_, _, filename_ = parts
if not filename_.startswith('/files'):
error = 'Changes should be prefixed with ' \
'/files if no context is provided,' \
' change: {0}'.format(change_)
raise ValueError(error)
filename_ = re.sub('^/files|/$', '', filename_)
if filename is not None:
if filename != filename_:
error = 'Changes should be made to one ' \
'file at a time, detected changes ' \
'to {0} and {1}'.format(filename, filename_)
raise ValueError(error)
filename = filename_
except (ValueError, IndexError) as err:
log.error(err)
if 'error' not in locals():
error = 'Invalid formatted command, ' \
'see debug log for details: {0}' \
.format(change_)
else:
error = six.text_type(err)
raise ValueError(error)
filename = _workout_filename(filename)
return filename | [
"def",
"_check_filepath",
"(",
"changes",
")",
":",
"filename",
"=",
"None",
"for",
"change_",
"in",
"changes",
":",
"try",
":",
"cmd",
",",
"arg",
"=",
"change_",
".",
"split",
"(",
"' '",
",",
"1",
")",
"if",
"cmd",
"not",
"in",
"METHOD_MAP",
":",
... | Ensure all changes are fully qualified and affect only one file.
This ensures that the diff output works and a state change is not
incorrectly reported. | [
"Ensure",
"all",
"changes",
"are",
"fully",
"qualified",
"and",
"affect",
"only",
"one",
"file",
".",
"This",
"ensures",
"that",
"the",
"diff",
"output",
"works",
"and",
"a",
"state",
"change",
"is",
"not",
"incorrectly",
"reported",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/augeas.py#L65-L110 | train |
saltstack/salt | salt/states/augeas.py | change | def change(name, context=None, changes=None, lens=None,
load_path=None, **kwargs):
'''
.. versionadded:: 2014.7.0
This state replaces :py:func:`~salt.states.augeas.setvalue`.
Issue changes to Augeas, optionally for a specific context, with a
specific lens.
name
State name
context
A file path, prefixed by ``/files``. Should resolve to an actual file
(not an arbitrary augeas path). This is used to avoid duplicating the
file name for each item in the changes list (for example, ``set bind 0.0.0.0``
in the example below operates on the file specified by ``context``). If
``context`` is not specified, a file path prefixed by ``/files`` should be
included with the ``set`` command.
The file path is examined to determine if the
specified changes are already present.
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set maxmemory 1G
changes
List of changes that are issued to Augeas. Available commands are
``set``, ``setm``, ``mv``/``move``, ``ins``/``insert``, and
``rm``/``remove``.
lens
The lens to use, needs to be suffixed with `.lns`, e.g.: `Nginx.lns`.
See the `list of stock lenses <http://augeas.net/stock_lenses.html>`_
shipped with Augeas.
.. versionadded:: 2016.3.0
load_path
A list of directories that modules should be searched in. This is in
addition to the standard load path and the directories in
AUGEAS_LENS_LIB.
Usage examples:
Set the ``bind`` parameter in ``/etc/redis/redis.conf``:
.. code-block:: yaml
redis-conf:
augeas.change:
- changes:
- set /files/etc/redis/redis.conf/bind 0.0.0.0
.. note::
Use the ``context`` parameter to specify the file you want to
manipulate. This way you don't have to include this in the changes
every time:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set databases 4
- set maxmemory 1G
Augeas is aware of a lot of common configuration files and their syntax.
It knows the difference between for example ini and yaml files, but also
files with very specific syntax, like the hosts file. This is done with
*lenses*, which provide mappings between the Augeas tree and the file.
There are many `preconfigured lenses`_ that come with Augeas by default,
and they specify the common locations for configuration files. So most
of the time Augeas will know how to manipulate a file. In the event that
you need to manipulate a file that Augeas doesn't know about, you can
specify the lens to use like this:
.. code-block:: yaml
redis-conf:
augeas.change:
- lens: redis.lns
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
.. note::
Even though Augeas knows that ``/etc/redis/redis.conf`` is a Redis
configuration file and knows how to parse it, it is recommended to
specify the lens anyway. This is because by default, Augeas loads all
known lenses and their associated file paths. All these files are
parsed when Augeas is loaded, which can take some time. When specifying
a lens, Augeas is loaded with only that lens, which speeds things up
quite a bit.
.. _preconfigured lenses: http://augeas.net/stock_lenses.html
A more complex example, this adds an entry to the services file for Zabbix,
and removes an obsolete service:
.. code-block:: yaml
zabbix-service:
augeas.change:
- lens: services.lns
- context: /files/etc/services
- changes:
- ins service-name after service-name[last()]
- set service-name[last()] "zabbix-agent"
- set "service-name[. = 'zabbix-agent']/port" 10050
- set "service-name[. = 'zabbix-agent']/protocol" tcp
- set "service-name[. = 'zabbix-agent']/#comment" "Zabbix Agent service"
- rm "service-name[. = 'im-obsolete']"
- unless: grep "zabbix-agent" /etc/services
.. warning::
Don't forget the ``unless`` here, otherwise it will fail on next runs
because the service is already defined. Additionally you have to quote
lines containing ``service-name[. = 'zabbix-agent']`` otherwise
:mod:`augeas_cfg <salt.modules.augeas_cfg>` execute will fail because
it will receive more parameters than expected.
.. note::
Order is important when defining a service with Augeas, in this case
it's ``port``, ``protocol`` and ``#comment``. For more info about
the lens check `services lens documentation`_.
.. _services lens documentation:
http://augeas.net/docs/references/lenses/files/services-aug.html#Services.record
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not changes or not isinstance(changes, list):
ret['comment'] = '\'changes\' must be specified as a list'
return ret
if load_path is not None:
if not isinstance(load_path, list):
ret['comment'] = '\'load_path\' must be specified as a list'
return ret
else:
load_path = ':'.join(load_path)
filename = None
if context is None:
try:
filename = _check_filepath(changes)
except ValueError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
else:
filename = re.sub('^/files|/$', '', context)
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Executing commands'
if context:
ret['comment'] += ' in file "{0}":\n'.format(context)
ret['comment'] += "\n".join(changes)
return ret
old_file = []
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
old_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
result = __salt__['augeas.execute'](
context=context, lens=lens,
commands=changes, load_path=load_path)
ret['result'] = result['retval']
if ret['result'] is False:
ret['comment'] = 'Error: {0}'.format(result['error'])
return ret
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
new_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
diff = ''.join(
difflib.unified_diff(old_file, new_file, n=0))
if diff:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'diff': diff}
else:
ret['comment'] = 'No changes made'
else:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'updates': changes}
return ret | python | def change(name, context=None, changes=None, lens=None,
load_path=None, **kwargs):
'''
.. versionadded:: 2014.7.0
This state replaces :py:func:`~salt.states.augeas.setvalue`.
Issue changes to Augeas, optionally for a specific context, with a
specific lens.
name
State name
context
A file path, prefixed by ``/files``. Should resolve to an actual file
(not an arbitrary augeas path). This is used to avoid duplicating the
file name for each item in the changes list (for example, ``set bind 0.0.0.0``
in the example below operates on the file specified by ``context``). If
``context`` is not specified, a file path prefixed by ``/files`` should be
included with the ``set`` command.
The file path is examined to determine if the
specified changes are already present.
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set maxmemory 1G
changes
List of changes that are issued to Augeas. Available commands are
``set``, ``setm``, ``mv``/``move``, ``ins``/``insert``, and
``rm``/``remove``.
lens
The lens to use, needs to be suffixed with `.lns`, e.g.: `Nginx.lns`.
See the `list of stock lenses <http://augeas.net/stock_lenses.html>`_
shipped with Augeas.
.. versionadded:: 2016.3.0
load_path
A list of directories that modules should be searched in. This is in
addition to the standard load path and the directories in
AUGEAS_LENS_LIB.
Usage examples:
Set the ``bind`` parameter in ``/etc/redis/redis.conf``:
.. code-block:: yaml
redis-conf:
augeas.change:
- changes:
- set /files/etc/redis/redis.conf/bind 0.0.0.0
.. note::
Use the ``context`` parameter to specify the file you want to
manipulate. This way you don't have to include this in the changes
every time:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set databases 4
- set maxmemory 1G
Augeas is aware of a lot of common configuration files and their syntax.
It knows the difference between for example ini and yaml files, but also
files with very specific syntax, like the hosts file. This is done with
*lenses*, which provide mappings between the Augeas tree and the file.
There are many `preconfigured lenses`_ that come with Augeas by default,
and they specify the common locations for configuration files. So most
of the time Augeas will know how to manipulate a file. In the event that
you need to manipulate a file that Augeas doesn't know about, you can
specify the lens to use like this:
.. code-block:: yaml
redis-conf:
augeas.change:
- lens: redis.lns
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
.. note::
Even though Augeas knows that ``/etc/redis/redis.conf`` is a Redis
configuration file and knows how to parse it, it is recommended to
specify the lens anyway. This is because by default, Augeas loads all
known lenses and their associated file paths. All these files are
parsed when Augeas is loaded, which can take some time. When specifying
a lens, Augeas is loaded with only that lens, which speeds things up
quite a bit.
.. _preconfigured lenses: http://augeas.net/stock_lenses.html
A more complex example, this adds an entry to the services file for Zabbix,
and removes an obsolete service:
.. code-block:: yaml
zabbix-service:
augeas.change:
- lens: services.lns
- context: /files/etc/services
- changes:
- ins service-name after service-name[last()]
- set service-name[last()] "zabbix-agent"
- set "service-name[. = 'zabbix-agent']/port" 10050
- set "service-name[. = 'zabbix-agent']/protocol" tcp
- set "service-name[. = 'zabbix-agent']/#comment" "Zabbix Agent service"
- rm "service-name[. = 'im-obsolete']"
- unless: grep "zabbix-agent" /etc/services
.. warning::
Don't forget the ``unless`` here, otherwise it will fail on next runs
because the service is already defined. Additionally you have to quote
lines containing ``service-name[. = 'zabbix-agent']`` otherwise
:mod:`augeas_cfg <salt.modules.augeas_cfg>` execute will fail because
it will receive more parameters than expected.
.. note::
Order is important when defining a service with Augeas, in this case
it's ``port``, ``protocol`` and ``#comment``. For more info about
the lens check `services lens documentation`_.
.. _services lens documentation:
http://augeas.net/docs/references/lenses/files/services-aug.html#Services.record
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not changes or not isinstance(changes, list):
ret['comment'] = '\'changes\' must be specified as a list'
return ret
if load_path is not None:
if not isinstance(load_path, list):
ret['comment'] = '\'load_path\' must be specified as a list'
return ret
else:
load_path = ':'.join(load_path)
filename = None
if context is None:
try:
filename = _check_filepath(changes)
except ValueError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
else:
filename = re.sub('^/files|/$', '', context)
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Executing commands'
if context:
ret['comment'] += ' in file "{0}":\n'.format(context)
ret['comment'] += "\n".join(changes)
return ret
old_file = []
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
old_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
result = __salt__['augeas.execute'](
context=context, lens=lens,
commands=changes, load_path=load_path)
ret['result'] = result['retval']
if ret['result'] is False:
ret['comment'] = 'Error: {0}'.format(result['error'])
return ret
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
new_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
diff = ''.join(
difflib.unified_diff(old_file, new_file, n=0))
if diff:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'diff': diff}
else:
ret['comment'] = 'No changes made'
else:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'updates': changes}
return ret | [
"def",
"change",
"(",
"name",
",",
"context",
"=",
"None",
",",
"changes",
"=",
"None",
",",
"lens",
"=",
"None",
",",
"load_path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"Fal... | .. versionadded:: 2014.7.0
This state replaces :py:func:`~salt.states.augeas.setvalue`.
Issue changes to Augeas, optionally for a specific context, with a
specific lens.
name
State name
context
A file path, prefixed by ``/files``. Should resolve to an actual file
(not an arbitrary augeas path). This is used to avoid duplicating the
file name for each item in the changes list (for example, ``set bind 0.0.0.0``
in the example below operates on the file specified by ``context``). If
``context`` is not specified, a file path prefixed by ``/files`` should be
included with the ``set`` command.
The file path is examined to determine if the
specified changes are already present.
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set maxmemory 1G
changes
List of changes that are issued to Augeas. Available commands are
``set``, ``setm``, ``mv``/``move``, ``ins``/``insert``, and
``rm``/``remove``.
lens
The lens to use, needs to be suffixed with `.lns`, e.g.: `Nginx.lns`.
See the `list of stock lenses <http://augeas.net/stock_lenses.html>`_
shipped with Augeas.
.. versionadded:: 2016.3.0
load_path
A list of directories that modules should be searched in. This is in
addition to the standard load path and the directories in
AUGEAS_LENS_LIB.
Usage examples:
Set the ``bind`` parameter in ``/etc/redis/redis.conf``:
.. code-block:: yaml
redis-conf:
augeas.change:
- changes:
- set /files/etc/redis/redis.conf/bind 0.0.0.0
.. note::
Use the ``context`` parameter to specify the file you want to
manipulate. This way you don't have to include this in the changes
every time:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set databases 4
- set maxmemory 1G
Augeas is aware of a lot of common configuration files and their syntax.
It knows the difference between for example ini and yaml files, but also
files with very specific syntax, like the hosts file. This is done with
*lenses*, which provide mappings between the Augeas tree and the file.
There are many `preconfigured lenses`_ that come with Augeas by default,
and they specify the common locations for configuration files. So most
of the time Augeas will know how to manipulate a file. In the event that
you need to manipulate a file that Augeas doesn't know about, you can
specify the lens to use like this:
.. code-block:: yaml
redis-conf:
augeas.change:
- lens: redis.lns
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
.. note::
Even though Augeas knows that ``/etc/redis/redis.conf`` is a Redis
configuration file and knows how to parse it, it is recommended to
specify the lens anyway. This is because by default, Augeas loads all
known lenses and their associated file paths. All these files are
parsed when Augeas is loaded, which can take some time. When specifying
a lens, Augeas is loaded with only that lens, which speeds things up
quite a bit.
.. _preconfigured lenses: http://augeas.net/stock_lenses.html
A more complex example, this adds an entry to the services file for Zabbix,
and removes an obsolete service:
.. code-block:: yaml
zabbix-service:
augeas.change:
- lens: services.lns
- context: /files/etc/services
- changes:
- ins service-name after service-name[last()]
- set service-name[last()] "zabbix-agent"
- set "service-name[. = 'zabbix-agent']/port" 10050
- set "service-name[. = 'zabbix-agent']/protocol" tcp
- set "service-name[. = 'zabbix-agent']/#comment" "Zabbix Agent service"
- rm "service-name[. = 'im-obsolete']"
- unless: grep "zabbix-agent" /etc/services
.. warning::
Don't forget the ``unless`` here, otherwise it will fail on next runs
because the service is already defined. Additionally you have to quote
lines containing ``service-name[. = 'zabbix-agent']`` otherwise
:mod:`augeas_cfg <salt.modules.augeas_cfg>` execute will fail because
it will receive more parameters than expected.
.. note::
Order is important when defining a service with Augeas, in this case
it's ``port``, ``protocol`` and ``#comment``. For more info about
the lens check `services lens documentation`_.
.. _services lens documentation:
http://augeas.net/docs/references/lenses/files/services-aug.html#Services.record | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/augeas.py#L113-L323 | train |
saltstack/salt | salt/modules/redismod.py | _connect | def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True) | python | def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True) | [
"def",
"_connect",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"not",
"host",
":",
"host",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'redis.host'",
")",
"if",
"... | Returns an instance of the redis client | [
"Returns",
"an",
"instance",
"of",
"the",
"redis",
"client"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L45-L58 | train |
saltstack/salt | salt/modules/redismod.py | _sconnect | def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True) | python | def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True) | [
"def",
"_sconnect",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"host",
"is",
"None",
":",
"host",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'redis_sentinel.host'",
",",
"'localhost'",
")",
... | Returns an instance of the redis client | [
"Returns",
"an",
"instance",
"of",
"the",
"redis",
"client"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L61-L72 | train |
saltstack/salt | salt/modules/redismod.py | bgrewriteaof | def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof() | python | def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof() | [
"def",
"bgrewriteaof",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
"."... | Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof | [
"Asynchronously",
"rewrite",
"the",
"append",
"-",
"only",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L75-L86 | train |
saltstack/salt | salt/modules/redismod.py | bgsave | def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave() | python | def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave() | [
"def",
"bgsave",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
".",
"b... | Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave | [
"Asynchronously",
"save",
"the",
"dataset",
"to",
"disk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L89-L100 | train |
saltstack/salt | salt/modules/redismod.py | config_get | def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern) | python | def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern) | [
"def",
"config_get",
"(",
"pattern",
"=",
"'*'",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
... | Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port | [
"Get",
"redis",
"server",
"configuration",
"values"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L103-L115 | train |
saltstack/salt | salt/modules/redismod.py | config_set | def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value) | python | def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value) | [
"def",
"config_set",
"(",
"name",
",",
"value",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
"... | Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens | [
"Set",
"redis",
"server",
"configuration",
"values"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L118-L129 | train |
saltstack/salt | salt/modules/redismod.py | dbsize | def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize() | python | def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize() | [
"def",
"dbsize",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
".",
"d... | Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize | [
"Return",
"the",
"number",
"of",
"keys",
"in",
"the",
"selected",
"database"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L132-L143 | train |
saltstack/salt | salt/modules/redismod.py | delete | def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys) | python | def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys) | [
"def",
"delete",
"(",
"*",
"keys",
",",
"*",
"*",
"connection_args",
")",
":",
"# Get connection args from keywords if set",
"conn_args",
"=",
"{",
"}",
"for",
"arg",
"in",
"[",
"'host'",
",",
"'port'",
",",
"'db'",
",",
"'password'",
"]",
":",
"if",
"arg"... | Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo | [
"Deletes",
"the",
"keys",
"from",
"redis",
"returns",
"number",
"of",
"keys",
"deleted"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L146-L163 | train |
saltstack/salt | salt/modules/redismod.py | exists | def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key) | python | def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key) | [
"def",
"exists",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"serv... | Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo | [
"Return",
"true",
"if",
"the",
"key",
"exists",
"in",
"redis"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L166-L177 | train |
saltstack/salt | salt/modules/redismod.py | expire | def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds) | python | def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds) | [
"def",
"expire",
"(",
"key",
",",
"seconds",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",... | Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300 | [
"Set",
"a",
"keys",
"time",
"to",
"live",
"in",
"seconds"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L180-L191 | train |
saltstack/salt | salt/modules/redismod.py | expireat | def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp) | python | def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp) | [
"def",
"expireat",
"(",
"key",
",",
"timestamp",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
... | Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000 | [
"Set",
"a",
"keys",
"expire",
"at",
"given",
"UNIX",
"time"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L194-L205 | train |
saltstack/salt | salt/modules/redismod.py | flushall | def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall() | python | def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall() | [
"def",
"flushall",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
".",
... | Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall | [
"Remove",
"all",
"keys",
"from",
"all",
"databases"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L208-L219 | train |
saltstack/salt | salt/modules/redismod.py | flushdb | def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb() | python | def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb() | [
"def",
"flushdb",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
".",
"... | Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb | [
"Remove",
"all",
"keys",
"from",
"the",
"selected",
"database"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L222-L233 | train |
saltstack/salt | salt/modules/redismod.py | get_key | def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key) | python | def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key) | [
"def",
"get_key",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"ser... | Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo | [
"Get",
"redis",
"key",
"value"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L236-L247 | train |
saltstack/salt | salt/modules/redismod.py | hexists | def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field) | python | def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field) | [
"def",
"hexists",
"(",
"key",
",",
"field",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
... | Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field | [
"Determine",
"if",
"a",
"hash",
"fields",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L270-L283 | train |
saltstack/salt | salt/modules/redismod.py | hgetall | def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key) | python | def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key) | [
"def",
"hgetall",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"ser... | Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash | [
"Get",
"all",
"fields",
"and",
"values",
"from",
"a",
"redis",
"hash",
"returns",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L300-L311 | train |
saltstack/salt | salt/modules/redismod.py | hincrby | def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment) | python | def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment) | [
"def",
"hincrby",
"(",
"key",
",",
"field",
",",
"increment",
"=",
"1",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
... | Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5 | [
"Increment",
"the",
"integer",
"value",
"of",
"a",
"hash",
"field",
"by",
"the",
"given",
"number",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L314-L327 | train |
saltstack/salt | salt/modules/redismod.py | hlen | def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key) | python | def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key) | [
"def",
"hlen",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server... | Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash | [
"Returns",
"number",
"of",
"fields",
"of",
"a",
"hash",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L346-L359 | train |
saltstack/salt | salt/modules/redismod.py | hmget | def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields) | python | def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields) | [
"def",
"hmget",
"(",
"key",
",",
"*",
"fields",
",",
"*",
"*",
"options",
")",
":",
"host",
"=",
"options",
".",
"get",
"(",
"'host'",
",",
"None",
")",
"port",
"=",
"options",
".",
"get",
"(",
"'port'",
",",
"None",
")",
"database",
"=",
"option... | Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2 | [
"Returns",
"the",
"values",
"of",
"all",
"the",
"given",
"hash",
"fields",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L362-L379 | train |
saltstack/salt | salt/modules/redismod.py | hmset | def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals)) | python | def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals)) | [
"def",
"hmset",
"(",
"key",
",",
"*",
"*",
"fieldsvals",
")",
":",
"host",
"=",
"fieldsvals",
".",
"pop",
"(",
"'host'",
",",
"None",
")",
"port",
"=",
"fieldsvals",
".",
"pop",
"(",
"'port'",
",",
"None",
")",
"database",
"=",
"fieldsvals",
".",
"... | Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2 | [
"Sets",
"multiple",
"hash",
"fields",
"to",
"multiple",
"values",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L382-L399 | train |
saltstack/salt | salt/modules/redismod.py | hset | def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value) | python | def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value) | [
"def",
"hset",
"(",
"key",
",",
"field",
",",
"value",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"pas... | Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value | [
"Set",
"the",
"value",
"of",
"a",
"hash",
"field",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L402-L415 | train |
saltstack/salt | salt/modules/redismod.py | hvals | def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key) | python | def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key) | [
"def",
"hvals",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"serve... | Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1 | [
"Return",
"all",
"the",
"values",
"in",
"a",
"hash",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L434-L447 | train |
saltstack/salt | salt/modules/redismod.py | hscan | def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count) | python | def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count) | [
"def",
"hscan",
"(",
"key",
",",
"cursor",
"=",
"0",
",",
"match",
"=",
"None",
",",
"count",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_conn... | Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1 | [
"Incrementally",
"iterate",
"hash",
"fields",
"and",
"associated",
"values",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L450-L463 | train |
saltstack/salt | salt/modules/redismod.py | info | def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info() | python | def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info() | [
"def",
"info",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
".",
"inf... | Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info | [
"Get",
"information",
"and",
"statistics",
"about",
"the",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L466-L477 | train |
saltstack/salt | salt/modules/redismod.py | keys | def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern) | python | def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern) | [
"def",
"keys",
"(",
"pattern",
"=",
"'*'",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
... | Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test* | [
"Get",
"redis",
"keys",
"supports",
"glob",
"style",
"patterns"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L480-L492 | train |
saltstack/salt | salt/modules/redismod.py | key_type | def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key) | python | def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key) | [
"def",
"key_type",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"se... | Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo | [
"Get",
"redis",
"key",
"type"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L495-L506 | train |
saltstack/salt | salt/modules/redismod.py | lastsave | def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp()) | python | def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp()) | [
"def",
"lastsave",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"# Use of %s to get the timestamp is not supported by Python. The reason it",
"# works is because it's passed to the system strftime which ... | Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave | [
"Get",
"the",
"UNIX",
"time",
"in",
"seconds",
"of",
"the",
"last",
"successful",
"save",
"to",
"disk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L509-L526 | train |
saltstack/salt | salt/modules/redismod.py | llen | def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key) | python | def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key) | [
"def",
"llen",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server... | Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list | [
"Get",
"the",
"length",
"of",
"a",
"list",
"in",
"Redis"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L529-L540 | train |
saltstack/salt | salt/modules/redismod.py | ping | def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False | python | def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False | [
"def",
"ping",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"try",
":",
"return",
"server... | Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping | [
"Ping",
"the",
"server",
"returns",
"False",
"on",
"connection",
"errors"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L557-L571 | train |
saltstack/salt | salt/modules/redismod.py | save | def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save() | python | def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save() | [
"def",
"save",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
".",
"sav... | Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save | [
"Synchronously",
"save",
"the",
"dataset",
"to",
"disk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L574-L585 | train |
saltstack/salt | salt/modules/redismod.py | set_key | def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value) | python | def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value) | [
"def",
"set_key",
"(",
"key",
",",
"value",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
... | Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar | [
"Set",
"redis",
"key",
"value"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L588-L599 | train |
saltstack/salt | salt/modules/redismod.py | shutdown | def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False | python | def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False | [
"def",
"shutdown",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"try",
":",
"# Return false... | Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown | [
"Synchronously",
"save",
"the",
"dataset",
"to",
"disk",
"and",
"then",
"shut",
"down",
"the",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L602-L625 | train |
saltstack/salt | salt/modules/redismod.py | slaveof | def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port) | python | def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port) | [
"def",
"slaveof",
"(",
"master_host",
"=",
"None",
",",
"master_port",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"master_host",
"and",
"not",
"master_port",
... | Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof | [
"Make",
"the",
"server",
"a",
"slave",
"of",
"another",
"instance",
"or",
"promote",
"it",
"as",
"master"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L628-L646 | train |
saltstack/salt | salt/modules/redismod.py | smembers | def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key)) | python | def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key)) | [
"def",
"smembers",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"li... | Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set | [
"Get",
"members",
"in",
"a",
"Redis",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L649-L660 | train |
saltstack/salt | salt/modules/redismod.py | time | def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0] | python | def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0] | [
"def",
"time",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
".",
"tim... | Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time | [
"Return",
"the",
"current",
"server",
"UNIX",
"time",
"in",
"seconds"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L663-L674 | train |
saltstack/salt | salt/modules/redismod.py | zcard | def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key) | python | def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key) | [
"def",
"zcard",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"serve... | Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted | [
"Get",
"the",
"length",
"of",
"a",
"sorted",
"set",
"in",
"Redis"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L677-L688 | train |
saltstack/salt | salt/modules/redismod.py | zrange | def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop) | python | def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop) | [
"def",
"zrange",
"(",
"key",
",",
"start",
",",
"stop",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"pa... | Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10 | [
"Get",
"a",
"range",
"of",
"values",
"from",
"a",
"sorted",
"set",
"in",
"Redis",
"by",
"index"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L691-L702 | train |
saltstack/salt | salt/modules/redismod.py | sentinel_get_master_ip | def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret))) | python | def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret))) | [
"def",
"sentinel_get_master_ip",
"(",
"master",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_sconnect",
"(",
"host",
",",
"port",
",",
"password",
")",
"ret",
"=",
"server",
".",
"sentinel... | Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster' | [
"Get",
"ip",
"for",
"sentinel",
"master"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L705-L719 | train |
saltstack/salt | salt/modules/redismod.py | get_master_ip | def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret))) | python | def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret))) | [
"def",
"get_master_ip",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"password",
")",
"srv_info",
"=",
"server",
".",
"info",
"(",
")",
"ret",
... | Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip | [
"Get",
"host",
"information",
"about",
"slave"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L722-L737 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.