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/quota.py | _parse_quota | def _parse_quota(mount, opts):
'''
Parse the output from repquota. Requires that -u -g are passed in
'''
cmd = 'repquota -vp {0} {1}'.format(opts, mount)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
mode = 'header'
if '-u' in opts:
quotatype = 'Users'
elif '-g' in opts:
quotatype = 'Groups'
ret = {quotatype: {}}
for line in out:
if not line:
continue
comps = line.split()
if mode == 'header':
if 'Block grace time' in line:
blockg, inodeg = line.split(';')
blockgc = blockg.split(': ')
inodegc = inodeg.split(': ')
ret['Block Grace Time'] = blockgc[-1:]
ret['Inode Grace Time'] = inodegc[-1:]
elif line.startswith('-'):
mode = 'quotas'
elif mode == 'quotas':
if len(comps) < 8:
continue
if not comps[0] in ret[quotatype]:
ret[quotatype][comps[0]] = {}
ret[quotatype][comps[0]]['block-used'] = comps[2]
ret[quotatype][comps[0]]['block-soft-limit'] = comps[3]
ret[quotatype][comps[0]]['block-hard-limit'] = comps[4]
ret[quotatype][comps[0]]['block-grace'] = comps[5]
ret[quotatype][comps[0]]['file-used'] = comps[6]
ret[quotatype][comps[0]]['file-soft-limit'] = comps[7]
ret[quotatype][comps[0]]['file-hard-limit'] = comps[8]
ret[quotatype][comps[0]]['file-grace'] = comps[9]
return ret | python | def _parse_quota(mount, opts):
'''
Parse the output from repquota. Requires that -u -g are passed in
'''
cmd = 'repquota -vp {0} {1}'.format(opts, mount)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
mode = 'header'
if '-u' in opts:
quotatype = 'Users'
elif '-g' in opts:
quotatype = 'Groups'
ret = {quotatype: {}}
for line in out:
if not line:
continue
comps = line.split()
if mode == 'header':
if 'Block grace time' in line:
blockg, inodeg = line.split(';')
blockgc = blockg.split(': ')
inodegc = inodeg.split(': ')
ret['Block Grace Time'] = blockgc[-1:]
ret['Inode Grace Time'] = inodegc[-1:]
elif line.startswith('-'):
mode = 'quotas'
elif mode == 'quotas':
if len(comps) < 8:
continue
if not comps[0] in ret[quotatype]:
ret[quotatype][comps[0]] = {}
ret[quotatype][comps[0]]['block-used'] = comps[2]
ret[quotatype][comps[0]]['block-soft-limit'] = comps[3]
ret[quotatype][comps[0]]['block-hard-limit'] = comps[4]
ret[quotatype][comps[0]]['block-grace'] = comps[5]
ret[quotatype][comps[0]]['file-used'] = comps[6]
ret[quotatype][comps[0]]['file-soft-limit'] = comps[7]
ret[quotatype][comps[0]]['file-hard-limit'] = comps[8]
ret[quotatype][comps[0]]['file-grace'] = comps[9]
return ret | [
"def",
"_parse_quota",
"(",
"mount",
",",
"opts",
")",
":",
"cmd",
"=",
"'repquota -vp {0} {1}'",
".",
"format",
"(",
"opts",
",",
"mount",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
".",
"sp... | Parse the output from repquota. Requires that -u -g are passed in | [
"Parse",
"the",
"output",
"from",
"repquota",
".",
"Requires",
"that",
"-",
"u",
"-",
"g",
"are",
"passed",
"in"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L54-L94 | train |
saltstack/salt | salt/modules/quota.py | set_ | def set_(device, **kwargs):
'''
Calls out to setquota, for a specific user or group
CLI Example:
.. code-block:: bash
salt '*' quota.set /media/data user=larry block-soft-limit=1048576
salt '*' quota.set /media/data group=painters file-hard-limit=1000
'''
empty = {'block-soft-limit': 0, 'block-hard-limit': 0,
'file-soft-limit': 0, 'file-hard-limit': 0}
current = None
cmd = 'setquota'
if 'user' in kwargs:
cmd += ' -u {0} '.format(kwargs['user'])
parsed = _parse_quota(device, '-u')
if kwargs['user'] in parsed:
current = parsed['Users'][kwargs['user']]
else:
current = empty
ret = 'User: {0}'.format(kwargs['user'])
if 'group' in kwargs:
if 'user' in kwargs:
raise SaltInvocationError(
'Please specify a user or group, not both.'
)
cmd += ' -g {0} '.format(kwargs['group'])
parsed = _parse_quota(device, '-g')
if kwargs['group'] in parsed:
current = parsed['Groups'][kwargs['group']]
else:
current = empty
ret = 'Group: {0}'.format(kwargs['group'])
if not current:
raise CommandExecutionError('A valid user or group was not found')
for limit in ('block-soft-limit', 'block-hard-limit',
'file-soft-limit', 'file-hard-limit'):
if limit in kwargs:
current[limit] = kwargs[limit]
cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'],
current['block-hard-limit'],
current['file-soft-limit'],
current['file-hard-limit'],
device)
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Unable to set desired quota. Error follows: \n{0}'
.format(result['stderr'])
)
return {ret: current} | python | def set_(device, **kwargs):
'''
Calls out to setquota, for a specific user or group
CLI Example:
.. code-block:: bash
salt '*' quota.set /media/data user=larry block-soft-limit=1048576
salt '*' quota.set /media/data group=painters file-hard-limit=1000
'''
empty = {'block-soft-limit': 0, 'block-hard-limit': 0,
'file-soft-limit': 0, 'file-hard-limit': 0}
current = None
cmd = 'setquota'
if 'user' in kwargs:
cmd += ' -u {0} '.format(kwargs['user'])
parsed = _parse_quota(device, '-u')
if kwargs['user'] in parsed:
current = parsed['Users'][kwargs['user']]
else:
current = empty
ret = 'User: {0}'.format(kwargs['user'])
if 'group' in kwargs:
if 'user' in kwargs:
raise SaltInvocationError(
'Please specify a user or group, not both.'
)
cmd += ' -g {0} '.format(kwargs['group'])
parsed = _parse_quota(device, '-g')
if kwargs['group'] in parsed:
current = parsed['Groups'][kwargs['group']]
else:
current = empty
ret = 'Group: {0}'.format(kwargs['group'])
if not current:
raise CommandExecutionError('A valid user or group was not found')
for limit in ('block-soft-limit', 'block-hard-limit',
'file-soft-limit', 'file-hard-limit'):
if limit in kwargs:
current[limit] = kwargs[limit]
cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'],
current['block-hard-limit'],
current['file-soft-limit'],
current['file-hard-limit'],
device)
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Unable to set desired quota. Error follows: \n{0}'
.format(result['stderr'])
)
return {ret: current} | [
"def",
"set_",
"(",
"device",
",",
"*",
"*",
"kwargs",
")",
":",
"empty",
"=",
"{",
"'block-soft-limit'",
":",
"0",
",",
"'block-hard-limit'",
":",
"0",
",",
"'file-soft-limit'",
":",
"0",
",",
"'file-hard-limit'",
":",
"0",
"}",
"current",
"=",
"None",
... | Calls out to setquota, for a specific user or group
CLI Example:
.. code-block:: bash
salt '*' quota.set /media/data user=larry block-soft-limit=1048576
salt '*' quota.set /media/data group=painters file-hard-limit=1000 | [
"Calls",
"out",
"to",
"setquota",
"for",
"a",
"specific",
"user",
"or",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L97-L155 | train |
saltstack/salt | salt/modules/quota.py | stats | def stats():
'''
Runs the quotastats command, and returns the parsed output
CLI Example:
.. code-block:: bash
salt '*' quota.stats
'''
ret = {}
out = __salt__['cmd.run']('quotastats').splitlines()
for line in out:
if not line:
continue
comps = line.split(': ')
ret[comps[0]] = comps[1]
return ret | python | def stats():
'''
Runs the quotastats command, and returns the parsed output
CLI Example:
.. code-block:: bash
salt '*' quota.stats
'''
ret = {}
out = __salt__['cmd.run']('quotastats').splitlines()
for line in out:
if not line:
continue
comps = line.split(': ')
ret[comps[0]] = comps[1]
return ret | [
"def",
"stats",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'quotastats'",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"out",
":",
"if",
"not",
"line",
":",
"continue",
"comps",
"=",
"line",
... | Runs the quotastats command, and returns the parsed output
CLI Example:
.. code-block:: bash
salt '*' quota.stats | [
"Runs",
"the",
"quotastats",
"command",
"and",
"returns",
"the",
"parsed",
"output"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L172-L190 | train |
saltstack/salt | salt/modules/quota.py | on | def on(device):
'''
Turns on the quota system
CLI Example:
.. code-block:: bash
salt '*' quota.on
'''
cmd = 'quotaon {0}'.format(device)
__salt__['cmd.run'](cmd, python_shell=False)
return True | python | def on(device):
'''
Turns on the quota system
CLI Example:
.. code-block:: bash
salt '*' quota.on
'''
cmd = 'quotaon {0}'.format(device)
__salt__['cmd.run'](cmd, python_shell=False)
return True | [
"def",
"on",
"(",
"device",
")",
":",
"cmd",
"=",
"'quotaon {0}'",
".",
"format",
"(",
"device",
")",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"return",
"True"
] | Turns on the quota system
CLI Example:
.. code-block:: bash
salt '*' quota.on | [
"Turns",
"on",
"the",
"quota",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L193-L205 | train |
saltstack/salt | salt/modules/quota.py | off | def off(device):
'''
Turns off the quota system
CLI Example:
.. code-block:: bash
salt '*' quota.off
'''
cmd = 'quotaoff {0}'.format(device)
__salt__['cmd.run'](cmd, python_shell=False)
return True | python | def off(device):
'''
Turns off the quota system
CLI Example:
.. code-block:: bash
salt '*' quota.off
'''
cmd = 'quotaoff {0}'.format(device)
__salt__['cmd.run'](cmd, python_shell=False)
return True | [
"def",
"off",
"(",
"device",
")",
":",
"cmd",
"=",
"'quotaoff {0}'",
".",
"format",
"(",
"device",
")",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"return",
"True"
] | Turns off the quota system
CLI Example:
.. code-block:: bash
salt '*' quota.off | [
"Turns",
"off",
"the",
"quota",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L208-L220 | train |
saltstack/salt | salt/modules/quota.py | get_mode | def get_mode(device):
'''
Report whether the quota system for this device is on or off
CLI Example:
.. code-block:: bash
salt '*' quota.get_mode
'''
ret = {}
cmd = 'quotaon -p {0}'.format(device)
out = __salt__['cmd.run'](cmd, python_shell=False)
for line in out.splitlines():
comps = line.strip().split()
if comps[3] not in ret:
if comps[0].startswith('quotaon'):
if comps[1].startswith('Mountpoint'):
ret[comps[4]] = 'disabled'
continue
elif comps[1].startswith('Cannot'):
ret[device] = 'Not found'
return ret
continue
ret[comps[3]] = {
'device': comps[4].replace('(', '').replace(')', ''),
}
ret[comps[3]][comps[0]] = comps[6]
return ret | python | def get_mode(device):
'''
Report whether the quota system for this device is on or off
CLI Example:
.. code-block:: bash
salt '*' quota.get_mode
'''
ret = {}
cmd = 'quotaon -p {0}'.format(device)
out = __salt__['cmd.run'](cmd, python_shell=False)
for line in out.splitlines():
comps = line.strip().split()
if comps[3] not in ret:
if comps[0].startswith('quotaon'):
if comps[1].startswith('Mountpoint'):
ret[comps[4]] = 'disabled'
continue
elif comps[1].startswith('Cannot'):
ret[device] = 'Not found'
return ret
continue
ret[comps[3]] = {
'device': comps[4].replace('(', '').replace(')', ''),
}
ret[comps[3]][comps[0]] = comps[6]
return ret | [
"def",
"get_mode",
"(",
"device",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'quotaon -p {0}'",
".",
"format",
"(",
"device",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"for",
"line",
"in... | Report whether the quota system for this device is on or off
CLI Example:
.. code-block:: bash
salt '*' quota.get_mode | [
"Report",
"whether",
"the",
"quota",
"system",
"for",
"this",
"device",
"is",
"on",
"or",
"off"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L223-L251 | train |
saltstack/salt | salt/states/pagerduty_user.py | present | def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure pagerduty user exists.
Arguments match those supported by
https://developer.pagerduty.com/documentation/rest/users/create.
'''
return __salt__['pagerduty_util.resource_present']('users',
['email', 'name', 'id'],
None,
profile,
subdomain,
api_key,
**kwargs) | python | def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure pagerduty user exists.
Arguments match those supported by
https://developer.pagerduty.com/documentation/rest/users/create.
'''
return __salt__['pagerduty_util.resource_present']('users',
['email', 'name', 'id'],
None,
profile,
subdomain,
api_key,
**kwargs) | [
"def",
"present",
"(",
"profile",
"=",
"'pagerduty'",
",",
"subdomain",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"__salt__",
"[",
"'pagerduty_util.resource_present'",
"]",
"(",
"'users'",
",",
"[",
"'email'",
"... | Ensure pagerduty user exists.
Arguments match those supported by
https://developer.pagerduty.com/documentation/rest/users/create. | [
"Ensure",
"pagerduty",
"user",
"exists",
".",
"Arguments",
"match",
"those",
"supported",
"by",
"https",
":",
"//",
"developer",
".",
"pagerduty",
".",
"com",
"/",
"documentation",
"/",
"rest",
"/",
"users",
"/",
"create",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_user.py#L28-L40 | train |
saltstack/salt | salt/modules/rsync.py | _check | def _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh):
'''
Generate rsync options
'''
options = ['-avz']
if delete:
options.append('--delete')
if force:
options.append('--force')
if update:
options.append('--update')
if rsh:
options.append('--rsh={0}'.format(rsh))
if passwordfile:
options.extend(['--password-file', passwordfile])
if excludefrom:
options.extend(['--exclude-from', excludefrom])
if exclude:
exclude = False
if exclude:
if isinstance(exclude, list):
for ex_ in exclude:
options.extend(['--exclude', ex_])
else:
options.extend(['--exclude', exclude])
if dryrun:
options.append('--dry-run')
return options | python | def _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh):
'''
Generate rsync options
'''
options = ['-avz']
if delete:
options.append('--delete')
if force:
options.append('--force')
if update:
options.append('--update')
if rsh:
options.append('--rsh={0}'.format(rsh))
if passwordfile:
options.extend(['--password-file', passwordfile])
if excludefrom:
options.extend(['--exclude-from', excludefrom])
if exclude:
exclude = False
if exclude:
if isinstance(exclude, list):
for ex_ in exclude:
options.extend(['--exclude', ex_])
else:
options.extend(['--exclude', exclude])
if dryrun:
options.append('--dry-run')
return options | [
"def",
"_check",
"(",
"delete",
",",
"force",
",",
"update",
",",
"passwordfile",
",",
"exclude",
",",
"excludefrom",
",",
"dryrun",
",",
"rsh",
")",
":",
"options",
"=",
"[",
"'-avz'",
"]",
"if",
"delete",
":",
"options",
".",
"append",
"(",
"'--delet... | Generate rsync options | [
"Generate",
"rsync",
"options"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rsync.py#L38-L66 | train |
saltstack/salt | salt/modules/rsync.py | rsync | def rsync(src,
dst,
delete=False,
force=False,
update=False,
passwordfile=None,
exclude=None,
excludefrom=None,
dryrun=False,
rsh=None,
additional_opts=None,
saltenv='base'):
'''
.. versionchanged:: 2016.3.0
Return data now contains just the output of the rsync command, instead
of a dictionary as returned from :py:func:`cmd.run_all
<salt.modules.cmdmod.run_all>`.
Rsync files from src to dst
src
The source location where files will be rsynced from.
dst
The destination location where files will be rsynced to.
delete : False
Whether to enable the rsync `--delete` flag, which
will delete extraneous files from dest dirs
force : False
Whether to enable the rsync `--force` flag, which
will force deletion of dirs even if not empty.
update : False
Whether to enable the rsync `--update` flag, which
forces rsync to skip any files which exist on the
destination and have a modified time that is newer
than the source file.
passwordfile
A file that contains a password for accessing an
rsync daemon. The file should contain just the
password.
exclude
Whether to enable the rsync `--exclude` flag, which
will exclude files matching a PATTERN.
excludefrom
Whether to enable the rsync `--excludefrom` flag, which
will read exclude patterns from a file.
dryrun : False
Whether to enable the rsync `--dry-run` flag, which
will perform a trial run with no changes made.
rsh
Whether to enable the rsync `--rsh` flag, to
specify the remote shell to use.
additional_opts
Any additional rsync options, should be specified as a list.
saltenv
Specify a salt fileserver environment to be used.
CLI Example:
.. code-block:: bash
salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir
salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini
salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]'
'''
if not src:
src = __salt__['config.option']('rsync.src')
if not dst:
dst = __salt__['config.option']('rsync.dst')
if not delete:
delete = __salt__['config.option']('rsync.delete')
if not force:
force = __salt__['config.option']('rsync.force')
if not update:
update = __salt__['config.option']('rsync.update')
if not passwordfile:
passwordfile = __salt__['config.option']('rsync.passwordfile')
if not exclude:
exclude = __salt__['config.option']('rsync.exclude')
if not excludefrom:
excludefrom = __salt__['config.option']('rsync.excludefrom')
if not dryrun:
dryrun = __salt__['config.option']('rsync.dryrun')
if not rsh:
rsh = __salt__['config.option']('rsync.rsh')
if not src or not dst:
raise SaltInvocationError('src and dst cannot be empty')
tmp_src = None
if src.startswith('salt://'):
_src = src
_path = re.sub('salt://', '', _src)
src_is_dir = False
if _path in __salt__['cp.list_master_dirs'](saltenv=saltenv):
src_is_dir = True
if src_is_dir:
tmp_src = tempfile.mkdtemp()
dir_src = __salt__['cp.get_dir'](_src,
tmp_src,
saltenv)
if dir_src:
src = tmp_src
# Ensure src ends in / so we
# get the contents not the tmpdir
# itself.
if not src.endswith('/'):
src = '{0}/'.format(src)
else:
raise CommandExecutionError('{0} does not exist'.format(src))
else:
tmp_src = salt.utils.files.mkstemp()
file_src = __salt__['cp.get_file'](_src,
tmp_src,
saltenv)
if file_src:
src = tmp_src
else:
raise CommandExecutionError('{0} does not exist'.format(src))
option = _check(delete,
force,
update,
passwordfile,
exclude,
excludefrom,
dryrun,
rsh)
if additional_opts and isinstance(additional_opts, list):
option = option + additional_opts
cmd = ['rsync'] + option + [src, dst]
log.debug('Running rsync command: %s', cmd)
try:
return __salt__['cmd.run_all'](cmd, python_shell=False)
except (IOError, OSError) as exc:
raise CommandExecutionError(exc.strerror)
finally:
if tmp_src:
__salt__['file.remove'](tmp_src) | python | def rsync(src,
dst,
delete=False,
force=False,
update=False,
passwordfile=None,
exclude=None,
excludefrom=None,
dryrun=False,
rsh=None,
additional_opts=None,
saltenv='base'):
'''
.. versionchanged:: 2016.3.0
Return data now contains just the output of the rsync command, instead
of a dictionary as returned from :py:func:`cmd.run_all
<salt.modules.cmdmod.run_all>`.
Rsync files from src to dst
src
The source location where files will be rsynced from.
dst
The destination location where files will be rsynced to.
delete : False
Whether to enable the rsync `--delete` flag, which
will delete extraneous files from dest dirs
force : False
Whether to enable the rsync `--force` flag, which
will force deletion of dirs even if not empty.
update : False
Whether to enable the rsync `--update` flag, which
forces rsync to skip any files which exist on the
destination and have a modified time that is newer
than the source file.
passwordfile
A file that contains a password for accessing an
rsync daemon. The file should contain just the
password.
exclude
Whether to enable the rsync `--exclude` flag, which
will exclude files matching a PATTERN.
excludefrom
Whether to enable the rsync `--excludefrom` flag, which
will read exclude patterns from a file.
dryrun : False
Whether to enable the rsync `--dry-run` flag, which
will perform a trial run with no changes made.
rsh
Whether to enable the rsync `--rsh` flag, to
specify the remote shell to use.
additional_opts
Any additional rsync options, should be specified as a list.
saltenv
Specify a salt fileserver environment to be used.
CLI Example:
.. code-block:: bash
salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir
salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini
salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]'
'''
if not src:
src = __salt__['config.option']('rsync.src')
if not dst:
dst = __salt__['config.option']('rsync.dst')
if not delete:
delete = __salt__['config.option']('rsync.delete')
if not force:
force = __salt__['config.option']('rsync.force')
if not update:
update = __salt__['config.option']('rsync.update')
if not passwordfile:
passwordfile = __salt__['config.option']('rsync.passwordfile')
if not exclude:
exclude = __salt__['config.option']('rsync.exclude')
if not excludefrom:
excludefrom = __salt__['config.option']('rsync.excludefrom')
if not dryrun:
dryrun = __salt__['config.option']('rsync.dryrun')
if not rsh:
rsh = __salt__['config.option']('rsync.rsh')
if not src or not dst:
raise SaltInvocationError('src and dst cannot be empty')
tmp_src = None
if src.startswith('salt://'):
_src = src
_path = re.sub('salt://', '', _src)
src_is_dir = False
if _path in __salt__['cp.list_master_dirs'](saltenv=saltenv):
src_is_dir = True
if src_is_dir:
tmp_src = tempfile.mkdtemp()
dir_src = __salt__['cp.get_dir'](_src,
tmp_src,
saltenv)
if dir_src:
src = tmp_src
# Ensure src ends in / so we
# get the contents not the tmpdir
# itself.
if not src.endswith('/'):
src = '{0}/'.format(src)
else:
raise CommandExecutionError('{0} does not exist'.format(src))
else:
tmp_src = salt.utils.files.mkstemp()
file_src = __salt__['cp.get_file'](_src,
tmp_src,
saltenv)
if file_src:
src = tmp_src
else:
raise CommandExecutionError('{0} does not exist'.format(src))
option = _check(delete,
force,
update,
passwordfile,
exclude,
excludefrom,
dryrun,
rsh)
if additional_opts and isinstance(additional_opts, list):
option = option + additional_opts
cmd = ['rsync'] + option + [src, dst]
log.debug('Running rsync command: %s', cmd)
try:
return __salt__['cmd.run_all'](cmd, python_shell=False)
except (IOError, OSError) as exc:
raise CommandExecutionError(exc.strerror)
finally:
if tmp_src:
__salt__['file.remove'](tmp_src) | [
"def",
"rsync",
"(",
"src",
",",
"dst",
",",
"delete",
"=",
"False",
",",
"force",
"=",
"False",
",",
"update",
"=",
"False",
",",
"passwordfile",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"excludefrom",
"=",
"None",
",",
"dryrun",
"=",
"False",... | .. versionchanged:: 2016.3.0
Return data now contains just the output of the rsync command, instead
of a dictionary as returned from :py:func:`cmd.run_all
<salt.modules.cmdmod.run_all>`.
Rsync files from src to dst
src
The source location where files will be rsynced from.
dst
The destination location where files will be rsynced to.
delete : False
Whether to enable the rsync `--delete` flag, which
will delete extraneous files from dest dirs
force : False
Whether to enable the rsync `--force` flag, which
will force deletion of dirs even if not empty.
update : False
Whether to enable the rsync `--update` flag, which
forces rsync to skip any files which exist on the
destination and have a modified time that is newer
than the source file.
passwordfile
A file that contains a password for accessing an
rsync daemon. The file should contain just the
password.
exclude
Whether to enable the rsync `--exclude` flag, which
will exclude files matching a PATTERN.
excludefrom
Whether to enable the rsync `--excludefrom` flag, which
will read exclude patterns from a file.
dryrun : False
Whether to enable the rsync `--dry-run` flag, which
will perform a trial run with no changes made.
rsh
Whether to enable the rsync `--rsh` flag, to
specify the remote shell to use.
additional_opts
Any additional rsync options, should be specified as a list.
saltenv
Specify a salt fileserver environment to be used.
CLI Example:
.. code-block:: bash
salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir
salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini
salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]' | [
"..",
"versionchanged",
"::",
"2016",
".",
"3",
".",
"0",
"Return",
"data",
"now",
"contains",
"just",
"the",
"output",
"of",
"the",
"rsync",
"command",
"instead",
"of",
"a",
"dictionary",
"as",
"returned",
"from",
":",
"py",
":",
"func",
":",
"cmd",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rsync.py#L69-L219 | train |
saltstack/salt | salt/modules/rsync.py | version | def version():
'''
.. versionchanged:: 2016.3.0
Return data now contains just the version number as a string, instead
of a dictionary as returned from :py:func:`cmd.run_all
<salt.modules.cmdmod.run_all>`.
Returns rsync version
CLI Example:
.. code-block:: bash
salt '*' rsync.version
'''
try:
out = __salt__['cmd.run_stdout'](
['rsync', '--version'],
python_shell=False)
except (IOError, OSError) as exc:
raise CommandExecutionError(exc.strerror)
try:
return out.split('\n')[0].split()[2]
except IndexError:
raise CommandExecutionError('Unable to determine rsync version') | python | def version():
'''
.. versionchanged:: 2016.3.0
Return data now contains just the version number as a string, instead
of a dictionary as returned from :py:func:`cmd.run_all
<salt.modules.cmdmod.run_all>`.
Returns rsync version
CLI Example:
.. code-block:: bash
salt '*' rsync.version
'''
try:
out = __salt__['cmd.run_stdout'](
['rsync', '--version'],
python_shell=False)
except (IOError, OSError) as exc:
raise CommandExecutionError(exc.strerror)
try:
return out.split('\n')[0].split()[2]
except IndexError:
raise CommandExecutionError('Unable to determine rsync version') | [
"def",
"version",
"(",
")",
":",
"try",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"[",
"'rsync'",
",",
"'--version'",
"]",
",",
"python_shell",
"=",
"False",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"exc",
":",
... | .. versionchanged:: 2016.3.0
Return data now contains just the version number as a string, instead
of a dictionary as returned from :py:func:`cmd.run_all
<salt.modules.cmdmod.run_all>`.
Returns rsync version
CLI Example:
.. code-block:: bash
salt '*' rsync.version | [
"..",
"versionchanged",
"::",
"2016",
".",
"3",
".",
"0",
"Return",
"data",
"now",
"contains",
"just",
"the",
"version",
"number",
"as",
"a",
"string",
"instead",
"of",
"a",
"dictionary",
"as",
"returned",
"from",
":",
"py",
":",
"func",
":",
"cmd",
".... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rsync.py#L222-L246 | train |
saltstack/salt | salt/modules/rsync.py | config | def config(conf_path='/etc/rsyncd.conf'):
'''
.. versionchanged:: 2016.3.0
Return data now contains just the contents of the rsyncd.conf as a
string, instead of a dictionary as returned from :py:func:`cmd.run_all
<salt.modules.cmdmod.run_all>`.
Returns the contents of the rsync config file
conf_path : /etc/rsyncd.conf
Path to the config file
CLI Example:
.. code-block:: bash
salt '*' rsync.config
'''
ret = ''
try:
with salt.utils.files.fopen(conf_path, 'r') as fp_:
for line in fp_:
ret += salt.utils.stringutils.to_unicode(line)
except IOError as exc:
if exc.errno == errno.ENOENT:
raise CommandExecutionError('{0} does not exist'.format(conf_path))
elif exc.errno == errno.EACCES:
raise CommandExecutionError(
'Unable to read {0}, access denied'.format(conf_path)
)
elif exc.errno == errno.EISDIR:
raise CommandExecutionError(
'Unable to read {0}, path is a directory'.format(conf_path)
)
else:
raise CommandExecutionError(
'Error {0}: {1}'.format(exc.errno, exc.strerror)
)
else:
return ret | python | def config(conf_path='/etc/rsyncd.conf'):
'''
.. versionchanged:: 2016.3.0
Return data now contains just the contents of the rsyncd.conf as a
string, instead of a dictionary as returned from :py:func:`cmd.run_all
<salt.modules.cmdmod.run_all>`.
Returns the contents of the rsync config file
conf_path : /etc/rsyncd.conf
Path to the config file
CLI Example:
.. code-block:: bash
salt '*' rsync.config
'''
ret = ''
try:
with salt.utils.files.fopen(conf_path, 'r') as fp_:
for line in fp_:
ret += salt.utils.stringutils.to_unicode(line)
except IOError as exc:
if exc.errno == errno.ENOENT:
raise CommandExecutionError('{0} does not exist'.format(conf_path))
elif exc.errno == errno.EACCES:
raise CommandExecutionError(
'Unable to read {0}, access denied'.format(conf_path)
)
elif exc.errno == errno.EISDIR:
raise CommandExecutionError(
'Unable to read {0}, path is a directory'.format(conf_path)
)
else:
raise CommandExecutionError(
'Error {0}: {1}'.format(exc.errno, exc.strerror)
)
else:
return ret | [
"def",
"config",
"(",
"conf_path",
"=",
"'/etc/rsyncd.conf'",
")",
":",
"ret",
"=",
"''",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"conf_path",
",",
"'r'",
")",
"as",
"fp_",
":",
"for",
"line",
"in",
"fp_",
":",
"r... | .. versionchanged:: 2016.3.0
Return data now contains just the contents of the rsyncd.conf as a
string, instead of a dictionary as returned from :py:func:`cmd.run_all
<salt.modules.cmdmod.run_all>`.
Returns the contents of the rsync config file
conf_path : /etc/rsyncd.conf
Path to the config file
CLI Example:
.. code-block:: bash
salt '*' rsync.config | [
"..",
"versionchanged",
"::",
"2016",
".",
"3",
".",
"0",
"Return",
"data",
"now",
"contains",
"just",
"the",
"contents",
"of",
"the",
"rsyncd",
".",
"conf",
"as",
"a",
"string",
"instead",
"of",
"a",
"dictionary",
"as",
"returned",
"from",
":",
"py",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rsync.py#L249-L288 | train |
saltstack/salt | salt/states/keystone_role.py | present | def present(name, auth=None, **kwargs):
'''
Ensure an role exists
name
Name of the role
description
An arbitrary description of the role
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_clouds'](auth)
kwargs['name'] = name
role = __salt__['keystoneng.role_get'](**kwargs)
if not role:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Role will be created.'
return ret
role = __salt__['keystoneng.role_create'](**kwargs)
ret['changes']['id'] = role.id
ret['changes']['name'] = role.name
ret['comment'] = 'Created role'
return ret
# NOTE(SamYaple): Update support pending https://review.openstack.org/#/c/496992/
return ret | python | def present(name, auth=None, **kwargs):
'''
Ensure an role exists
name
Name of the role
description
An arbitrary description of the role
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_clouds'](auth)
kwargs['name'] = name
role = __salt__['keystoneng.role_get'](**kwargs)
if not role:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Role will be created.'
return ret
role = __salt__['keystoneng.role_create'](**kwargs)
ret['changes']['id'] = role.id
ret['changes']['name'] = role.name
ret['comment'] = 'Created role'
return ret
# NOTE(SamYaple): Update support pending https://review.openstack.org/#/c/496992/
return ret | [
"def",
"present",
"(",
"name",
",",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"kwargs",
"=",
... | Ensure an role exists
name
Name of the role
description
An arbitrary description of the role | [
"Ensure",
"an",
"role",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_role.py#L40-L75 | train |
saltstack/salt | salt/states/keystone_role.py | absent | def absent(name, auth=None, **kwargs):
'''
Ensure role does not exist
name
Name of the role
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
kwargs['name'] = name
role = __salt__['keystoneng.role_get'](**kwargs)
if role:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'id': role.id}
ret['comment'] = 'Role will be deleted.'
return ret
__salt__['keystoneng.role_delete'](name=role)
ret['changes']['id'] = role.id
ret['comment'] = 'Deleted role'
return ret | python | def absent(name, auth=None, **kwargs):
'''
Ensure role does not exist
name
Name of the role
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
kwargs['name'] = name
role = __salt__['keystoneng.role_get'](**kwargs)
if role:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'id': role.id}
ret['comment'] = 'Role will be deleted.'
return ret
__salt__['keystoneng.role_delete'](name=role)
ret['changes']['id'] = role.id
ret['comment'] = 'Deleted role'
return ret | [
"def",
"absent",
"(",
"name",
",",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"__salt__",
"[",
... | Ensure role does not exist
name
Name of the role | [
"Ensure",
"role",
"does",
"not",
"exist"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_role.py#L78-L106 | train |
saltstack/salt | salt/modules/mac_assistive.py | install | def install(app_id, enable=True):
'''
Install a bundle ID or command as being allowed to use
assistive access.
app_id
The bundle ID or command to install for assistive access.
enabled
Sets enabled or disabled status. Default is ``True``.
CLI Example:
.. code-block:: bash
salt '*' assistive.install /usr/bin/osascript
salt '*' assistive.install com.smileonmymac.textexpander
'''
ge_el_capitan = True if _LooseVersion(__grains__['osrelease']) >= salt.utils.stringutils.to_str('10.11') else False
client_type = _client_type(app_id)
enable_str = '1' if enable else '0'
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \
'"INSERT or REPLACE INTO access VALUES(\'kTCCServiceAccessibility\',\'{0}\',{1},{2},1,NULL{3})"'.\
format(app_id, client_type, enable_str, ',NULL' if ge_el_capitan else '')
call = __salt__['cmd.run_all'](
cmd,
output_loglevel='debug',
python_shell=False
)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError('Error installing app: {0}'.format(comment))
return True | python | def install(app_id, enable=True):
'''
Install a bundle ID or command as being allowed to use
assistive access.
app_id
The bundle ID or command to install for assistive access.
enabled
Sets enabled or disabled status. Default is ``True``.
CLI Example:
.. code-block:: bash
salt '*' assistive.install /usr/bin/osascript
salt '*' assistive.install com.smileonmymac.textexpander
'''
ge_el_capitan = True if _LooseVersion(__grains__['osrelease']) >= salt.utils.stringutils.to_str('10.11') else False
client_type = _client_type(app_id)
enable_str = '1' if enable else '0'
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \
'"INSERT or REPLACE INTO access VALUES(\'kTCCServiceAccessibility\',\'{0}\',{1},{2},1,NULL{3})"'.\
format(app_id, client_type, enable_str, ',NULL' if ge_el_capitan else '')
call = __salt__['cmd.run_all'](
cmd,
output_loglevel='debug',
python_shell=False
)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError('Error installing app: {0}'.format(comment))
return True | [
"def",
"install",
"(",
"app_id",
",",
"enable",
"=",
"True",
")",
":",
"ge_el_capitan",
"=",
"True",
"if",
"_LooseVersion",
"(",
"__grains__",
"[",
"'osrelease'",
"]",
")",
">=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str",
"(",
"'10.11'",
")... | Install a bundle ID or command as being allowed to use
assistive access.
app_id
The bundle ID or command to install for assistive access.
enabled
Sets enabled or disabled status. Default is ``True``.
CLI Example:
.. code-block:: bash
salt '*' assistive.install /usr/bin/osascript
salt '*' assistive.install com.smileonmymac.textexpander | [
"Install",
"a",
"bundle",
"ID",
"or",
"command",
"as",
"being",
"allowed",
"to",
"use",
"assistive",
"access",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_assistive.py#L39-L78 | train |
saltstack/salt | salt/modules/mac_assistive.py | enable | def enable(app_id, enabled=True):
'''
Enable or disable an existing assistive access application.
app_id
The bundle ID or command to set assistive access status.
enabled
Sets enabled or disabled status. Default is ``True``.
CLI Example:
.. code-block:: bash
salt '*' assistive.enable /usr/bin/osascript
salt '*' assistive.enable com.smileonmymac.textexpander enabled=False
'''
enable_str = '1' if enabled else '0'
for a in _get_assistive_access():
if app_id == a[0]:
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \
'"UPDATE access SET allowed=\'{0}\' WHERE client=\'{1}\'"'.format(enable_str, app_id)
call = __salt__['cmd.run_all'](
cmd,
output_loglevel='debug',
python_shell=False
)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError('Error enabling app: {0}'.format(comment))
return True
return False | python | def enable(app_id, enabled=True):
'''
Enable or disable an existing assistive access application.
app_id
The bundle ID or command to set assistive access status.
enabled
Sets enabled or disabled status. Default is ``True``.
CLI Example:
.. code-block:: bash
salt '*' assistive.enable /usr/bin/osascript
salt '*' assistive.enable com.smileonmymac.textexpander enabled=False
'''
enable_str = '1' if enabled else '0'
for a in _get_assistive_access():
if app_id == a[0]:
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \
'"UPDATE access SET allowed=\'{0}\' WHERE client=\'{1}\'"'.format(enable_str, app_id)
call = __salt__['cmd.run_all'](
cmd,
output_loglevel='debug',
python_shell=False
)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError('Error enabling app: {0}'.format(comment))
return True
return False | [
"def",
"enable",
"(",
"app_id",
",",
"enabled",
"=",
"True",
")",
":",
"enable_str",
"=",
"'1'",
"if",
"enabled",
"else",
"'0'",
"for",
"a",
"in",
"_get_assistive_access",
"(",
")",
":",
"if",
"app_id",
"==",
"a",
"[",
"0",
"]",
":",
"cmd",
"=",
"'... | Enable or disable an existing assistive access application.
app_id
The bundle ID or command to set assistive access status.
enabled
Sets enabled or disabled status. Default is ``True``.
CLI Example:
.. code-block:: bash
salt '*' assistive.enable /usr/bin/osascript
salt '*' assistive.enable com.smileonmymac.textexpander enabled=False | [
"Enable",
"or",
"disable",
"an",
"existing",
"assistive",
"access",
"application",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_assistive.py#L103-L143 | train |
saltstack/salt | salt/modules/mac_assistive.py | remove | def remove(app_id):
'''
Remove a bundle ID or command as being allowed to use assistive access.
app_id
The bundle ID or command to remove from assistive access list.
CLI Example:
.. code-block:: bash
salt '*' assistive.remove /usr/bin/osascript
salt '*' assistive.remove com.smileonmymac.textexpander
'''
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \
'"DELETE from access where client=\'{0}\'"'.format(app_id)
call = __salt__['cmd.run_all'](
cmd,
output_loglevel='debug',
python_shell=False
)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError('Error removing app: {0}'.format(comment))
return True | python | def remove(app_id):
'''
Remove a bundle ID or command as being allowed to use assistive access.
app_id
The bundle ID or command to remove from assistive access list.
CLI Example:
.. code-block:: bash
salt '*' assistive.remove /usr/bin/osascript
salt '*' assistive.remove com.smileonmymac.textexpander
'''
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \
'"DELETE from access where client=\'{0}\'"'.format(app_id)
call = __salt__['cmd.run_all'](
cmd,
output_loglevel='debug',
python_shell=False
)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError('Error removing app: {0}'.format(comment))
return True | [
"def",
"remove",
"(",
"app_id",
")",
":",
"cmd",
"=",
"'sqlite3 \"/Library/Application Support/com.apple.TCC/TCC.db\" '",
"'\"DELETE from access where client=\\'{0}\\'\"'",
".",
"format",
"(",
"app_id",
")",
"call",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
... | Remove a bundle ID or command as being allowed to use assistive access.
app_id
The bundle ID or command to remove from assistive access list.
CLI Example:
.. code-block:: bash
salt '*' assistive.remove /usr/bin/osascript
salt '*' assistive.remove com.smileonmymac.textexpander | [
"Remove",
"a",
"bundle",
"ID",
"or",
"command",
"as",
"being",
"allowed",
"to",
"use",
"assistive",
"access",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_assistive.py#L168-L199 | train |
saltstack/salt | salt/modules/mac_assistive.py | _get_assistive_access | def _get_assistive_access():
'''
Get a list of all of the assistive access applications installed,
returns as a ternary showing whether each app is enabled or not.
'''
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT * FROM access"'
call = __salt__['cmd.run_all'](
cmd,
output_loglevel='debug',
python_shell=False
)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError('Error: {0}'.format(comment))
out = call['stdout']
return re.findall(r'kTCCServiceAccessibility\|(.*)\|[0-9]{1}\|([0-9]{1})\|[0-9]{1}\|', out, re.MULTILINE) | python | def _get_assistive_access():
'''
Get a list of all of the assistive access applications installed,
returns as a ternary showing whether each app is enabled or not.
'''
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT * FROM access"'
call = __salt__['cmd.run_all'](
cmd,
output_loglevel='debug',
python_shell=False
)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError('Error: {0}'.format(comment))
out = call['stdout']
return re.findall(r'kTCCServiceAccessibility\|(.*)\|[0-9]{1}\|([0-9]{1})\|[0-9]{1}\|', out, re.MULTILINE) | [
"def",
"_get_assistive_access",
"(",
")",
":",
"cmd",
"=",
"'sqlite3 \"/Library/Application Support/com.apple.TCC/TCC.db\" \"SELECT * FROM access\"'",
"call",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"output_loglevel",
"=",
"'debug'",
",",
"python_shell"... | Get a list of all of the assistive access applications installed,
returns as a ternary showing whether each app is enabled or not. | [
"Get",
"a",
"list",
"of",
"all",
"of",
"the",
"assistive",
"access",
"applications",
"installed",
"returns",
"as",
"a",
"ternary",
"showing",
"whether",
"each",
"app",
"is",
"enabled",
"or",
"not",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_assistive.py#L210-L232 | train |
saltstack/salt | salt/serializers/yaml.py | deserialize | def deserialize(stream_or_string, **options):
'''
Deserialize any string of stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower yaml module.
'''
options.setdefault('Loader', Loader)
try:
return yaml.load(stream_or_string, **options)
except ScannerError as error:
log.exception('Error encountered while deserializing')
err_type = ERROR_MAP.get(error.problem, 'Unknown yaml render error')
line_num = error.problem_mark.line + 1
raise DeserializationError(err_type,
line_num,
error.problem_mark.buffer)
except ConstructorError as error:
log.exception('Error encountered while deserializing')
raise DeserializationError(error)
except Exception as error:
log.exception('Error encountered while deserializing')
raise DeserializationError(error) | python | def deserialize(stream_or_string, **options):
'''
Deserialize any string of stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower yaml module.
'''
options.setdefault('Loader', Loader)
try:
return yaml.load(stream_or_string, **options)
except ScannerError as error:
log.exception('Error encountered while deserializing')
err_type = ERROR_MAP.get(error.problem, 'Unknown yaml render error')
line_num = error.problem_mark.line + 1
raise DeserializationError(err_type,
line_num,
error.problem_mark.buffer)
except ConstructorError as error:
log.exception('Error encountered while deserializing')
raise DeserializationError(error)
except Exception as error:
log.exception('Error encountered while deserializing')
raise DeserializationError(error) | [
"def",
"deserialize",
"(",
"stream_or_string",
",",
"*",
"*",
"options",
")",
":",
"options",
".",
"setdefault",
"(",
"'Loader'",
",",
"Loader",
")",
"try",
":",
"return",
"yaml",
".",
"load",
"(",
"stream_or_string",
",",
"*",
"*",
"options",
")",
"exce... | Deserialize any string of stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower yaml module. | [
"Deserialize",
"any",
"string",
"of",
"stream",
"like",
"object",
"into",
"a",
"Python",
"data",
"structure",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/yaml.py#L41-L64 | train |
saltstack/salt | salt/serializers/yaml.py | serialize | def serialize(obj, **options):
'''
Serialize Python data to YAML.
:param obj: the data structure to serialize
:param options: options given to lower yaml module.
'''
options.setdefault('Dumper', Dumper)
try:
response = yaml.dump(obj, **options)
if response.endswith('\n...\n'):
return response[:-5]
if response.endswith('\n'):
return response[:-1]
return response
except Exception as error:
log.exception('Error encountered while serializing')
raise SerializationError(error) | python | def serialize(obj, **options):
'''
Serialize Python data to YAML.
:param obj: the data structure to serialize
:param options: options given to lower yaml module.
'''
options.setdefault('Dumper', Dumper)
try:
response = yaml.dump(obj, **options)
if response.endswith('\n...\n'):
return response[:-5]
if response.endswith('\n'):
return response[:-1]
return response
except Exception as error:
log.exception('Error encountered while serializing')
raise SerializationError(error) | [
"def",
"serialize",
"(",
"obj",
",",
"*",
"*",
"options",
")",
":",
"options",
".",
"setdefault",
"(",
"'Dumper'",
",",
"Dumper",
")",
"try",
":",
"response",
"=",
"yaml",
".",
"dump",
"(",
"obj",
",",
"*",
"*",
"options",
")",
"if",
"response",
".... | Serialize Python data to YAML.
:param obj: the data structure to serialize
:param options: options given to lower yaml module. | [
"Serialize",
"Python",
"data",
"to",
"YAML",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/yaml.py#L67-L85 | train |
saltstack/salt | salt/modules/win_certutil.py | get_cert_serial | def get_cert_serial(cert_file):
'''
Get the serial number of a certificate file
cert_file
The certificate file to find the serial for
CLI Example:
.. code-block:: bash
salt '*' certutil.get_cert_serial <certificate name>
'''
cmd = "certutil.exe -silent -verify {0}".format(cert_file)
out = __salt__['cmd.run'](cmd)
# match serial number by paragraph to work with multiple languages
matches = re.search(r":\s*(\w*)\r\n\r\n", out)
if matches is not None:
return matches.groups()[0].strip()
else:
return None | python | def get_cert_serial(cert_file):
'''
Get the serial number of a certificate file
cert_file
The certificate file to find the serial for
CLI Example:
.. code-block:: bash
salt '*' certutil.get_cert_serial <certificate name>
'''
cmd = "certutil.exe -silent -verify {0}".format(cert_file)
out = __salt__['cmd.run'](cmd)
# match serial number by paragraph to work with multiple languages
matches = re.search(r":\s*(\w*)\r\n\r\n", out)
if matches is not None:
return matches.groups()[0].strip()
else:
return None | [
"def",
"get_cert_serial",
"(",
"cert_file",
")",
":",
"cmd",
"=",
"\"certutil.exe -silent -verify {0}\"",
".",
"format",
"(",
"cert_file",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
"# match serial number by paragraph to work with multiple lang... | Get the serial number of a certificate file
cert_file
The certificate file to find the serial for
CLI Example:
.. code-block:: bash
salt '*' certutil.get_cert_serial <certificate name> | [
"Get",
"the",
"serial",
"number",
"of",
"a",
"certificate",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_certutil.py#L32-L52 | train |
saltstack/salt | salt/modules/win_certutil.py | get_stored_cert_serials | def get_stored_cert_serials(store):
'''
Get all of the certificate serials in the specified store
store
The store to get all the certificate serials from
CLI Example:
.. code-block:: bash
salt '*' certutil.get_stored_cert_serials <store>
'''
cmd = "certutil.exe -store {0}".format(store)
out = __salt__['cmd.run'](cmd)
# match serial numbers by header position to work with multiple languages
matches = re.findall(r"={16}\r\n.*:\s*(\w*)\r\n", out)
return matches | python | def get_stored_cert_serials(store):
'''
Get all of the certificate serials in the specified store
store
The store to get all the certificate serials from
CLI Example:
.. code-block:: bash
salt '*' certutil.get_stored_cert_serials <store>
'''
cmd = "certutil.exe -store {0}".format(store)
out = __salt__['cmd.run'](cmd)
# match serial numbers by header position to work with multiple languages
matches = re.findall(r"={16}\r\n.*:\s*(\w*)\r\n", out)
return matches | [
"def",
"get_stored_cert_serials",
"(",
"store",
")",
":",
"cmd",
"=",
"\"certutil.exe -store {0}\"",
".",
"format",
"(",
"store",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
"# match serial numbers by header position to work with multiple langua... | Get all of the certificate serials in the specified store
store
The store to get all the certificate serials from
CLI Example:
.. code-block:: bash
salt '*' certutil.get_stored_cert_serials <store> | [
"Get",
"all",
"of",
"the",
"certificate",
"serials",
"in",
"the",
"specified",
"store"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_certutil.py#L55-L72 | train |
saltstack/salt | salt/modules/win_certutil.py | add_store | def add_store(source, store, saltenv='base'):
'''
Add the given cert into the given Certificate Store
source
The source certificate file this can be in the form
salt://path/to/file
store
The certificate store to add the certificate to
saltenv
The salt environment to use this is ignored if the path
is local
CLI Example:
.. code-block:: bash
salt '*' certutil.add_store salt://cert.cer TrustedPublisher
'''
cert_file = __salt__['cp.cache_file'](source, saltenv)
cmd = "certutil.exe -addstore {0} {1}".format(store, cert_file)
return __salt__['cmd.run'](cmd) | python | def add_store(source, store, saltenv='base'):
'''
Add the given cert into the given Certificate Store
source
The source certificate file this can be in the form
salt://path/to/file
store
The certificate store to add the certificate to
saltenv
The salt environment to use this is ignored if the path
is local
CLI Example:
.. code-block:: bash
salt '*' certutil.add_store salt://cert.cer TrustedPublisher
'''
cert_file = __salt__['cp.cache_file'](source, saltenv)
cmd = "certutil.exe -addstore {0} {1}".format(store, cert_file)
return __salt__['cmd.run'](cmd) | [
"def",
"add_store",
"(",
"source",
",",
"store",
",",
"saltenv",
"=",
"'base'",
")",
":",
"cert_file",
"=",
"__salt__",
"[",
"'cp.cache_file'",
"]",
"(",
"source",
",",
"saltenv",
")",
"cmd",
"=",
"\"certutil.exe -addstore {0} {1}\"",
".",
"format",
"(",
"st... | Add the given cert into the given Certificate Store
source
The source certificate file this can be in the form
salt://path/to/file
store
The certificate store to add the certificate to
saltenv
The salt environment to use this is ignored if the path
is local
CLI Example:
.. code-block:: bash
salt '*' certutil.add_store salt://cert.cer TrustedPublisher | [
"Add",
"the",
"given",
"cert",
"into",
"the",
"given",
"Certificate",
"Store"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_certutil.py#L75-L98 | train |
saltstack/salt | salt/modules/win_certutil.py | del_store | def del_store(source, store, saltenv='base'):
'''
Delete the given cert into the given Certificate Store
source
The source certificate file this can be in the form
salt://path/to/file
store
The certificate store to delete the certificate from
saltenv
The salt environment to use this is ignored if the path
is local
CLI Example:
.. code-block:: bash
salt '*' certutil.del_store salt://cert.cer TrustedPublisher
'''
cert_file = __salt__['cp.cache_file'](source, saltenv)
serial = get_cert_serial(cert_file)
cmd = "certutil.exe -delstore {0} {1}".format(store, serial)
return __salt__['cmd.run'](cmd) | python | def del_store(source, store, saltenv='base'):
'''
Delete the given cert into the given Certificate Store
source
The source certificate file this can be in the form
salt://path/to/file
store
The certificate store to delete the certificate from
saltenv
The salt environment to use this is ignored if the path
is local
CLI Example:
.. code-block:: bash
salt '*' certutil.del_store salt://cert.cer TrustedPublisher
'''
cert_file = __salt__['cp.cache_file'](source, saltenv)
serial = get_cert_serial(cert_file)
cmd = "certutil.exe -delstore {0} {1}".format(store, serial)
return __salt__['cmd.run'](cmd) | [
"def",
"del_store",
"(",
"source",
",",
"store",
",",
"saltenv",
"=",
"'base'",
")",
":",
"cert_file",
"=",
"__salt__",
"[",
"'cp.cache_file'",
"]",
"(",
"source",
",",
"saltenv",
")",
"serial",
"=",
"get_cert_serial",
"(",
"cert_file",
")",
"cmd",
"=",
... | Delete the given cert into the given Certificate Store
source
The source certificate file this can be in the form
salt://path/to/file
store
The certificate store to delete the certificate from
saltenv
The salt environment to use this is ignored if the path
is local
CLI Example:
.. code-block:: bash
salt '*' certutil.del_store salt://cert.cer TrustedPublisher | [
"Delete",
"the",
"given",
"cert",
"into",
"the",
"given",
"Certificate",
"Store"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_certutil.py#L101-L125 | train |
saltstack/salt | salt/states/ddns.py | present | def present(name, zone, ttl, data, rdtype='A', **kwargs):
'''
Ensures that the named DNS record is present with the given ttl.
name
The host portion of the DNS record, e.g., 'webserver'. Name and zone
are concatenated when the entry is created unless name includes a
trailing dot, so make sure that information is not duplicated in these
two arguments.
zone
The zone to check/update
ttl
TTL for the record
data
Data for the DNS record. E.g., the IP address for an A record.
rdtype
DNS resource type. Default 'A'.
``**kwargs``
Additional arguments the ddns.update function may need (e.g.
nameserver, keyfile, keyname). Note that the nsupdate key file can’t
be reused by this function, the keyfile and other arguments must
follow the `dnspython <http://www.dnspython.org/>`_ spec.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['result'] = None
ret['comment'] = '{0} record "{1}" will be updated'.format(rdtype, name)
return ret
status = __salt__['ddns.update'](zone, name, ttl, rdtype, data, **kwargs)
if status is None:
ret['result'] = True
ret['comment'] = '{0} record "{1}" already present with ttl of {2}'.format(
rdtype, name, ttl)
elif status:
ret['result'] = True
ret['comment'] = 'Updated {0} record for "{1}"'.format(rdtype, name)
ret['changes'] = {'name': name,
'zone': zone,
'ttl': ttl,
'rdtype': rdtype,
'data': data
}
else:
ret['result'] = False
ret['comment'] = 'Failed to create or update {0} record for "{1}"'.format(rdtype, name)
return ret | python | def present(name, zone, ttl, data, rdtype='A', **kwargs):
'''
Ensures that the named DNS record is present with the given ttl.
name
The host portion of the DNS record, e.g., 'webserver'. Name and zone
are concatenated when the entry is created unless name includes a
trailing dot, so make sure that information is not duplicated in these
two arguments.
zone
The zone to check/update
ttl
TTL for the record
data
Data for the DNS record. E.g., the IP address for an A record.
rdtype
DNS resource type. Default 'A'.
``**kwargs``
Additional arguments the ddns.update function may need (e.g.
nameserver, keyfile, keyname). Note that the nsupdate key file can’t
be reused by this function, the keyfile and other arguments must
follow the `dnspython <http://www.dnspython.org/>`_ spec.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['result'] = None
ret['comment'] = '{0} record "{1}" will be updated'.format(rdtype, name)
return ret
status = __salt__['ddns.update'](zone, name, ttl, rdtype, data, **kwargs)
if status is None:
ret['result'] = True
ret['comment'] = '{0} record "{1}" already present with ttl of {2}'.format(
rdtype, name, ttl)
elif status:
ret['result'] = True
ret['comment'] = 'Updated {0} record for "{1}"'.format(rdtype, name)
ret['changes'] = {'name': name,
'zone': zone,
'ttl': ttl,
'rdtype': rdtype,
'data': data
}
else:
ret['result'] = False
ret['comment'] = 'Failed to create or update {0} record for "{1}"'.format(rdtype, name)
return ret | [
"def",
"present",
"(",
"name",
",",
"zone",
",",
"ttl",
",",
"data",
",",
"rdtype",
"=",
"'A'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'co... | Ensures that the named DNS record is present with the given ttl.
name
The host portion of the DNS record, e.g., 'webserver'. Name and zone
are concatenated when the entry is created unless name includes a
trailing dot, so make sure that information is not duplicated in these
two arguments.
zone
The zone to check/update
ttl
TTL for the record
data
Data for the DNS record. E.g., the IP address for an A record.
rdtype
DNS resource type. Default 'A'.
``**kwargs``
Additional arguments the ddns.update function may need (e.g.
nameserver, keyfile, keyname). Note that the nsupdate key file can’t
be reused by this function, the keyfile and other arguments must
follow the `dnspython <http://www.dnspython.org/>`_ spec. | [
"Ensures",
"that",
"the",
"named",
"DNS",
"record",
"is",
"present",
"with",
"the",
"given",
"ttl",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ddns.py#L35-L91 | train |
saltstack/salt | salt/states/ddns.py | absent | def absent(name, zone, data=None, rdtype=None, **kwargs):
'''
Ensures that the named DNS record is absent.
name
The host portion of the DNS record, e.g., 'webserver'. Name and zone
are concatenated when the entry is created unless name includes a
trailing dot, so make sure that information is not duplicated in these
two arguments.
zone
The zone to check
data
Data for the DNS record. E.g., the IP address for an A record. If omitted,
all records matching name (and rdtype, if provided) will be purged.
rdtype
DNS resource type. If omitted, all types will be purged.
``**kwargs``
Additional arguments the ddns.update function may need (e.g.
nameserver, keyfile, keyname). Note that the nsupdate key file can’t
be reused by this function, the keyfile and other arguments must
follow the `dnspython <http://www.dnspython.org/>`_ spec.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['result'] = None
ret['comment'] = '{0} record "{1}" will be deleted'.format(rdtype, name)
return ret
status = __salt__['ddns.delete'](zone, name, rdtype, data, **kwargs)
if status is None:
ret['result'] = True
ret['comment'] = 'No matching DNS record(s) present'
elif status:
ret['result'] = True
ret['comment'] = 'Deleted DNS record(s)'
ret['changes'] = {'Deleted': {'name': name,
'zone': zone
}
}
else:
ret['result'] = False
ret['comment'] = 'Failed to delete DNS record(s)'
return ret | python | def absent(name, zone, data=None, rdtype=None, **kwargs):
'''
Ensures that the named DNS record is absent.
name
The host portion of the DNS record, e.g., 'webserver'. Name and zone
are concatenated when the entry is created unless name includes a
trailing dot, so make sure that information is not duplicated in these
two arguments.
zone
The zone to check
data
Data for the DNS record. E.g., the IP address for an A record. If omitted,
all records matching name (and rdtype, if provided) will be purged.
rdtype
DNS resource type. If omitted, all types will be purged.
``**kwargs``
Additional arguments the ddns.update function may need (e.g.
nameserver, keyfile, keyname). Note that the nsupdate key file can’t
be reused by this function, the keyfile and other arguments must
follow the `dnspython <http://www.dnspython.org/>`_ spec.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['result'] = None
ret['comment'] = '{0} record "{1}" will be deleted'.format(rdtype, name)
return ret
status = __salt__['ddns.delete'](zone, name, rdtype, data, **kwargs)
if status is None:
ret['result'] = True
ret['comment'] = 'No matching DNS record(s) present'
elif status:
ret['result'] = True
ret['comment'] = 'Deleted DNS record(s)'
ret['changes'] = {'Deleted': {'name': name,
'zone': zone
}
}
else:
ret['result'] = False
ret['comment'] = 'Failed to delete DNS record(s)'
return ret | [
"def",
"absent",
"(",
"name",
",",
"zone",
",",
"data",
"=",
"None",
",",
"rdtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'c... | Ensures that the named DNS record is absent.
name
The host portion of the DNS record, e.g., 'webserver'. Name and zone
are concatenated when the entry is created unless name includes a
trailing dot, so make sure that information is not duplicated in these
two arguments.
zone
The zone to check
data
Data for the DNS record. E.g., the IP address for an A record. If omitted,
all records matching name (and rdtype, if provided) will be purged.
rdtype
DNS resource type. If omitted, all types will be purged.
``**kwargs``
Additional arguments the ddns.update function may need (e.g.
nameserver, keyfile, keyname). Note that the nsupdate key file can’t
be reused by this function, the keyfile and other arguments must
follow the `dnspython <http://www.dnspython.org/>`_ spec. | [
"Ensures",
"that",
"the",
"named",
"DNS",
"record",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ddns.py#L94-L145 | train |
saltstack/salt | salt/renderers/json.py | render | def render(json_data, saltenv='base', sls='', **kws):
'''
Accepts JSON as a string or as a file object and runs it through the JSON
parser.
:rtype: A Python data structure
'''
if not isinstance(json_data, six.string_types):
json_data = json_data.read()
if json_data.startswith('#!'):
json_data = json_data[(json_data.find('\n') + 1):]
if not json_data.strip():
return {}
return json.loads(json_data) | python | def render(json_data, saltenv='base', sls='', **kws):
'''
Accepts JSON as a string or as a file object and runs it through the JSON
parser.
:rtype: A Python data structure
'''
if not isinstance(json_data, six.string_types):
json_data = json_data.read()
if json_data.startswith('#!'):
json_data = json_data[(json_data.find('\n') + 1):]
if not json_data.strip():
return {}
return json.loads(json_data) | [
"def",
"render",
"(",
"json_data",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"*",
"*",
"kws",
")",
":",
"if",
"not",
"isinstance",
"(",
"json_data",
",",
"six",
".",
"string_types",
")",
":",
"json_data",
"=",
"json_data",
".",
"read... | Accepts JSON as a string or as a file object and runs it through the JSON
parser.
:rtype: A Python data structure | [
"Accepts",
"JSON",
"as",
"a",
"string",
"or",
"as",
"a",
"file",
"object",
"and",
"runs",
"it",
"through",
"the",
"JSON",
"parser",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/json.py#L16-L30 | train |
saltstack/salt | salt/modules/at.py | _cmd | def _cmd(binary, *args):
'''
Wrapper to run at(1) or return None.
'''
binary = salt.utils.path.which(binary)
if not binary:
raise CommandNotFoundError('{0}: command not found'.format(binary))
cmd = [binary] + list(args)
return __salt__['cmd.run_stdout']([binary] + list(args),
python_shell=False) | python | def _cmd(binary, *args):
'''
Wrapper to run at(1) or return None.
'''
binary = salt.utils.path.which(binary)
if not binary:
raise CommandNotFoundError('{0}: command not found'.format(binary))
cmd = [binary] + list(args)
return __salt__['cmd.run_stdout']([binary] + list(args),
python_shell=False) | [
"def",
"_cmd",
"(",
"binary",
",",
"*",
"args",
")",
":",
"binary",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"binary",
")",
"if",
"not",
"binary",
":",
"raise",
"CommandNotFoundError",
"(",
"'{0}: command not found'",
".",
"format",
"("... | Wrapper to run at(1) or return None. | [
"Wrapper",
"to",
"run",
"at",
"(",
"1",
")",
"or",
"return",
"None",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L51-L60 | train |
saltstack/salt | salt/modules/at.py | atq | def atq(tag=None):
'''
List all queued and running jobs or only those with
an optional 'tag'.
CLI Example:
.. code-block:: bash
salt '*' at.atq
salt '*' at.atq [tag]
salt '*' at.atq [job number]
'''
jobs = []
# Shim to produce output similar to what __virtual__() should do
# but __salt__ isn't available in __virtual__()
# Tested on CentOS 5.8
if __grains__['os_family'] == 'RedHat':
output = _cmd('at', '-l')
else:
output = _cmd('atq')
if output is None:
return '\'at.atq\' is not available.'
# No jobs so return
if output == '':
return {'jobs': jobs}
# Jobs created with at.at() will use the following
# comment to denote a tagged job.
job_kw_regex = re.compile(r'^### SALT: (\w+)')
# Split each job into a dictionary and handle
# pulling out tags or only listing jobs with a certain
# tag
for line in output.splitlines():
job_tag = ''
# Redhat/CentOS
if __grains__['os_family'] == 'RedHat':
job, spec = line.split('\t')
specs = spec.split()
elif __grains__['os'] == 'OpenBSD':
if line.startswith(' Rank'):
continue
else:
tmp = line.split()
timestr = ' '.join(tmp[1:5])
job = tmp[6]
specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y '
'%H:%M')[0:5])).isoformat().split('T')
specs.append(tmp[7])
specs.append(tmp[5])
elif __grains__['os'] == 'FreeBSD':
if line.startswith('Date'):
continue
else:
tmp = line.split()
timestr = ' '.join(tmp[1:6])
job = tmp[8]
specs = datetime.datetime(*(time.strptime(timestr,
'%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T')
specs.append(tmp[7])
specs.append(tmp[6])
else:
job, spec = line.split('\t')
tmp = spec.split()
timestr = ' '.join(tmp[0:5])
specs = datetime.datetime(*(time.strptime(timestr)
[0:5])).isoformat().split('T')
specs.append(tmp[5])
specs.append(tmp[6])
# Search for any tags
atc_out = _cmd('at', '-c', job)
for line in atc_out.splitlines():
tmp = job_kw_regex.match(line)
if tmp:
job_tag = tmp.groups()[0]
if __grains__['os'] in BSD:
job = six.text_type(job)
else:
job = int(job)
# If a tag is supplied, only list jobs with that tag
if tag:
# TODO: Looks like there is a difference between salt and salt-call
# If I don't wrap job in an int(), it fails on salt but works on
# salt-call. With the int(), it fails with salt-call but not salt.
if tag == job_tag or tag == job:
jobs.append({'job': job, 'date': specs[0], 'time': specs[1],
'queue': specs[2], 'user': specs[3], 'tag': job_tag})
else:
jobs.append({'job': job, 'date': specs[0], 'time': specs[1],
'queue': specs[2], 'user': specs[3], 'tag': job_tag})
return {'jobs': jobs} | python | def atq(tag=None):
'''
List all queued and running jobs or only those with
an optional 'tag'.
CLI Example:
.. code-block:: bash
salt '*' at.atq
salt '*' at.atq [tag]
salt '*' at.atq [job number]
'''
jobs = []
# Shim to produce output similar to what __virtual__() should do
# but __salt__ isn't available in __virtual__()
# Tested on CentOS 5.8
if __grains__['os_family'] == 'RedHat':
output = _cmd('at', '-l')
else:
output = _cmd('atq')
if output is None:
return '\'at.atq\' is not available.'
# No jobs so return
if output == '':
return {'jobs': jobs}
# Jobs created with at.at() will use the following
# comment to denote a tagged job.
job_kw_regex = re.compile(r'^### SALT: (\w+)')
# Split each job into a dictionary and handle
# pulling out tags or only listing jobs with a certain
# tag
for line in output.splitlines():
job_tag = ''
# Redhat/CentOS
if __grains__['os_family'] == 'RedHat':
job, spec = line.split('\t')
specs = spec.split()
elif __grains__['os'] == 'OpenBSD':
if line.startswith(' Rank'):
continue
else:
tmp = line.split()
timestr = ' '.join(tmp[1:5])
job = tmp[6]
specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y '
'%H:%M')[0:5])).isoformat().split('T')
specs.append(tmp[7])
specs.append(tmp[5])
elif __grains__['os'] == 'FreeBSD':
if line.startswith('Date'):
continue
else:
tmp = line.split()
timestr = ' '.join(tmp[1:6])
job = tmp[8]
specs = datetime.datetime(*(time.strptime(timestr,
'%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T')
specs.append(tmp[7])
specs.append(tmp[6])
else:
job, spec = line.split('\t')
tmp = spec.split()
timestr = ' '.join(tmp[0:5])
specs = datetime.datetime(*(time.strptime(timestr)
[0:5])).isoformat().split('T')
specs.append(tmp[5])
specs.append(tmp[6])
# Search for any tags
atc_out = _cmd('at', '-c', job)
for line in atc_out.splitlines():
tmp = job_kw_regex.match(line)
if tmp:
job_tag = tmp.groups()[0]
if __grains__['os'] in BSD:
job = six.text_type(job)
else:
job = int(job)
# If a tag is supplied, only list jobs with that tag
if tag:
# TODO: Looks like there is a difference between salt and salt-call
# If I don't wrap job in an int(), it fails on salt but works on
# salt-call. With the int(), it fails with salt-call but not salt.
if tag == job_tag or tag == job:
jobs.append({'job': job, 'date': specs[0], 'time': specs[1],
'queue': specs[2], 'user': specs[3], 'tag': job_tag})
else:
jobs.append({'job': job, 'date': specs[0], 'time': specs[1],
'queue': specs[2], 'user': specs[3], 'tag': job_tag})
return {'jobs': jobs} | [
"def",
"atq",
"(",
"tag",
"=",
"None",
")",
":",
"jobs",
"=",
"[",
"]",
"# Shim to produce output similar to what __virtual__() should do",
"# but __salt__ isn't available in __virtual__()",
"# Tested on CentOS 5.8",
"if",
"__grains__",
"[",
"'os_family'",
"]",
"==",
"'RedH... | List all queued and running jobs or only those with
an optional 'tag'.
CLI Example:
.. code-block:: bash
salt '*' at.atq
salt '*' at.atq [tag]
salt '*' at.atq [job number] | [
"List",
"all",
"queued",
"and",
"running",
"jobs",
"or",
"only",
"those",
"with",
"an",
"optional",
"tag",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L63-L163 | train |
saltstack/salt | salt/modules/at.py | atrm | def atrm(*args):
'''
Remove jobs from the queue.
CLI Example:
.. code-block:: bash
salt '*' at.atrm <jobid> <jobid> .. <jobid>
salt '*' at.atrm all
salt '*' at.atrm all [tag]
'''
# Need to do this here also since we use atq()
if not salt.utils.path.which('at'):
return '\'at.atrm\' is not available.'
if not args:
return {'jobs': {'removed': [], 'tag': None}}
# Convert all to strings
args = salt.utils.data.stringify(args)
if args[0] == 'all':
if len(args) > 1:
opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']])))
ret = {'jobs': {'removed': opts, 'tag': args[1]}}
else:
opts = list(list(map(str, [j['job'] for j in atq()['jobs']])))
ret = {'jobs': {'removed': opts, 'tag': None}}
else:
opts = list(list(map(str, [i['job'] for i in atq()['jobs']
if six.text_type(i['job']) in args])))
ret = {'jobs': {'removed': opts, 'tag': None}}
# Shim to produce output similar to what __virtual__() should do
# but __salt__ isn't available in __virtual__()
output = _cmd('at', '-d', ' '.join(opts))
if output is None:
return '\'at.atrm\' is not available.'
return ret | python | def atrm(*args):
'''
Remove jobs from the queue.
CLI Example:
.. code-block:: bash
salt '*' at.atrm <jobid> <jobid> .. <jobid>
salt '*' at.atrm all
salt '*' at.atrm all [tag]
'''
# Need to do this here also since we use atq()
if not salt.utils.path.which('at'):
return '\'at.atrm\' is not available.'
if not args:
return {'jobs': {'removed': [], 'tag': None}}
# Convert all to strings
args = salt.utils.data.stringify(args)
if args[0] == 'all':
if len(args) > 1:
opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']])))
ret = {'jobs': {'removed': opts, 'tag': args[1]}}
else:
opts = list(list(map(str, [j['job'] for j in atq()['jobs']])))
ret = {'jobs': {'removed': opts, 'tag': None}}
else:
opts = list(list(map(str, [i['job'] for i in atq()['jobs']
if six.text_type(i['job']) in args])))
ret = {'jobs': {'removed': opts, 'tag': None}}
# Shim to produce output similar to what __virtual__() should do
# but __salt__ isn't available in __virtual__()
output = _cmd('at', '-d', ' '.join(opts))
if output is None:
return '\'at.atrm\' is not available.'
return ret | [
"def",
"atrm",
"(",
"*",
"args",
")",
":",
"# Need to do this here also since we use atq()",
"if",
"not",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'at'",
")",
":",
"return",
"'\\'at.atrm\\' is not available.'",
"if",
"not",
"args",
":",
"return",
... | Remove jobs from the queue.
CLI Example:
.. code-block:: bash
salt '*' at.atrm <jobid> <jobid> .. <jobid>
salt '*' at.atrm all
salt '*' at.atrm all [tag] | [
"Remove",
"jobs",
"from",
"the",
"queue",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L166-L207 | train |
saltstack/salt | salt/modules/at.py | at | def at(*args, **kwargs): # pylint: disable=C0103
'''
Add a job to the queue.
The 'timespec' follows the format documented in the
at(1) manpage.
CLI Example:
.. code-block:: bash
salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>]
salt '*' at.at 12:05am '/sbin/reboot' tag=reboot
salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim
'''
if len(args) < 2:
return {'jobs': []}
# Shim to produce output similar to what __virtual__() should do
# but __salt__ isn't available in __virtual__()
binary = salt.utils.path.which('at')
if not binary:
return '\'at.at\' is not available.'
if 'tag' in kwargs:
stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:]))
else:
stdin = ' '.join(args[1:])
cmd = [binary, args[0]]
cmd_kwargs = {'stdin': stdin, 'python_shell': False}
if 'runas' in kwargs:
cmd_kwargs['runas'] = kwargs['runas']
output = __salt__['cmd.run'](cmd, **cmd_kwargs)
if output is None:
return '\'at.at\' is not available.'
if output.endswith('Garbled time'):
return {'jobs': [], 'error': 'invalid timespec'}
if output.startswith('warning: commands'):
output = output.splitlines()[1]
if output.startswith('commands will be executed'):
output = output.splitlines()[1]
output = output.split()[1]
if __grains__['os'] in BSD:
return atq(six.text_type(output))
else:
return atq(int(output)) | python | def at(*args, **kwargs): # pylint: disable=C0103
'''
Add a job to the queue.
The 'timespec' follows the format documented in the
at(1) manpage.
CLI Example:
.. code-block:: bash
salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>]
salt '*' at.at 12:05am '/sbin/reboot' tag=reboot
salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim
'''
if len(args) < 2:
return {'jobs': []}
# Shim to produce output similar to what __virtual__() should do
# but __salt__ isn't available in __virtual__()
binary = salt.utils.path.which('at')
if not binary:
return '\'at.at\' is not available.'
if 'tag' in kwargs:
stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:]))
else:
stdin = ' '.join(args[1:])
cmd = [binary, args[0]]
cmd_kwargs = {'stdin': stdin, 'python_shell': False}
if 'runas' in kwargs:
cmd_kwargs['runas'] = kwargs['runas']
output = __salt__['cmd.run'](cmd, **cmd_kwargs)
if output is None:
return '\'at.at\' is not available.'
if output.endswith('Garbled time'):
return {'jobs': [], 'error': 'invalid timespec'}
if output.startswith('warning: commands'):
output = output.splitlines()[1]
if output.startswith('commands will be executed'):
output = output.splitlines()[1]
output = output.split()[1]
if __grains__['os'] in BSD:
return atq(six.text_type(output))
else:
return atq(int(output)) | [
"def",
"at",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0103",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"return",
"{",
"'jobs'",
":",
"[",
"]",
"}",
"# Shim to produce output similar to what __virtual__() should do",
"# but _... | Add a job to the queue.
The 'timespec' follows the format documented in the
at(1) manpage.
CLI Example:
.. code-block:: bash
salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>]
salt '*' at.at 12:05am '/sbin/reboot' tag=reboot
salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim | [
"Add",
"a",
"job",
"to",
"the",
"queue",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L210-L263 | train |
saltstack/salt | salt/modules/at.py | atc | def atc(jobid):
'''
Print the at(1) script that will run for the passed job
id. This is mostly for debugging so the output will
just be text.
CLI Example:
.. code-block:: bash
salt '*' at.atc <jobid>
'''
# Shim to produce output similar to what __virtual__() should do
# but __salt__ isn't available in __virtual__()
output = _cmd('at', '-c', six.text_type(jobid))
if output is None:
return '\'at.atc\' is not available.'
elif output == '':
return {'error': 'invalid job id \'{0}\''.format(jobid)}
return output | python | def atc(jobid):
'''
Print the at(1) script that will run for the passed job
id. This is mostly for debugging so the output will
just be text.
CLI Example:
.. code-block:: bash
salt '*' at.atc <jobid>
'''
# Shim to produce output similar to what __virtual__() should do
# but __salt__ isn't available in __virtual__()
output = _cmd('at', '-c', six.text_type(jobid))
if output is None:
return '\'at.atc\' is not available.'
elif output == '':
return {'error': 'invalid job id \'{0}\''.format(jobid)}
return output | [
"def",
"atc",
"(",
"jobid",
")",
":",
"# Shim to produce output similar to what __virtual__() should do",
"# but __salt__ isn't available in __virtual__()",
"output",
"=",
"_cmd",
"(",
"'at'",
",",
"'-c'",
",",
"six",
".",
"text_type",
"(",
"jobid",
")",
")",
"if",
"o... | Print the at(1) script that will run for the passed job
id. This is mostly for debugging so the output will
just be text.
CLI Example:
.. code-block:: bash
salt '*' at.atc <jobid> | [
"Print",
"the",
"at",
"(",
"1",
")",
"script",
"that",
"will",
"run",
"for",
"the",
"passed",
"job",
"id",
".",
"This",
"is",
"mostly",
"for",
"debugging",
"so",
"the",
"output",
"will",
"just",
"be",
"text",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L266-L287 | train |
saltstack/salt | salt/modules/at.py | _atq | def _atq(**kwargs):
'''
Return match jobs list
'''
jobs = []
runas = kwargs.get('runas', None)
tag = kwargs.get('tag', None)
hour = kwargs.get('hour', None)
minute = kwargs.get('minute', None)
day = kwargs.get('day', None)
month = kwargs.get('month', None)
year = kwargs.get('year', None)
if year and len(six.text_type(year)) == 2:
year = '20{0}'.format(year)
jobinfo = atq()['jobs']
if not jobinfo:
return {'jobs': jobs}
for job in jobinfo:
if not runas:
pass
elif runas == job['user']:
pass
else:
continue
if not tag:
pass
elif tag == job['tag']:
pass
else:
continue
if not hour:
pass
elif '{0:02d}'.format(int(hour)) == job['time'].split(':')[0]:
pass
else:
continue
if not minute:
pass
elif '{0:02d}'.format(int(minute)) == job['time'].split(':')[1]:
pass
else:
continue
if not day:
pass
elif '{0:02d}'.format(int(day)) == job['date'].split('-')[2]:
pass
else:
continue
if not month:
pass
elif '{0:02d}'.format(int(month)) == job['date'].split('-')[1]:
pass
else:
continue
if not year:
pass
elif year == job['date'].split('-')[0]:
pass
else:
continue
jobs.append(job)
if not jobs:
note = 'No match jobs or time format error'
return {'jobs': jobs, 'note': note}
return {'jobs': jobs} | python | def _atq(**kwargs):
'''
Return match jobs list
'''
jobs = []
runas = kwargs.get('runas', None)
tag = kwargs.get('tag', None)
hour = kwargs.get('hour', None)
minute = kwargs.get('minute', None)
day = kwargs.get('day', None)
month = kwargs.get('month', None)
year = kwargs.get('year', None)
if year and len(six.text_type(year)) == 2:
year = '20{0}'.format(year)
jobinfo = atq()['jobs']
if not jobinfo:
return {'jobs': jobs}
for job in jobinfo:
if not runas:
pass
elif runas == job['user']:
pass
else:
continue
if not tag:
pass
elif tag == job['tag']:
pass
else:
continue
if not hour:
pass
elif '{0:02d}'.format(int(hour)) == job['time'].split(':')[0]:
pass
else:
continue
if not minute:
pass
elif '{0:02d}'.format(int(minute)) == job['time'].split(':')[1]:
pass
else:
continue
if not day:
pass
elif '{0:02d}'.format(int(day)) == job['date'].split('-')[2]:
pass
else:
continue
if not month:
pass
elif '{0:02d}'.format(int(month)) == job['date'].split('-')[1]:
pass
else:
continue
if not year:
pass
elif year == job['date'].split('-')[0]:
pass
else:
continue
jobs.append(job)
if not jobs:
note = 'No match jobs or time format error'
return {'jobs': jobs, 'note': note}
return {'jobs': jobs} | [
"def",
"_atq",
"(",
"*",
"*",
"kwargs",
")",
":",
"jobs",
"=",
"[",
"]",
"runas",
"=",
"kwargs",
".",
"get",
"(",
"'runas'",
",",
"None",
")",
"tag",
"=",
"kwargs",
".",
"get",
"(",
"'tag'",
",",
"None",
")",
"hour",
"=",
"kwargs",
".",
"get",
... | Return match jobs list | [
"Return",
"match",
"jobs",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L290-L368 | train |
saltstack/salt | salt/cli/support/__init__.py | _render_profile | def _render_profile(path, caller, runner):
'''
Render profile as Jinja2.
:param path:
:return:
'''
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False)
return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip() | python | def _render_profile(path, caller, runner):
'''
Render profile as Jinja2.
:param path:
:return:
'''
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False)
return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip() | [
"def",
"_render_profile",
"(",
"path",
",",
"caller",
",",
"runner",
")",
":",
"env",
"=",
"jinja2",
".",
"Environment",
"(",
"loader",
"=",
"jinja2",
".",
"FileSystemLoader",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
",",
"trim_bl... | Render profile as Jinja2.
:param path:
:return: | [
"Render",
"profile",
"as",
"Jinja2",
".",
":",
"param",
"path",
":",
":",
"return",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/__init__.py#L15-L22 | train |
saltstack/salt | salt/cli/support/__init__.py | get_profile | def get_profile(profile, caller, runner):
'''
Get profile.
:param profile:
:return:
'''
profiles = profile.split(',')
data = {}
for profile in profiles:
if os.path.basename(profile) == profile:
profile = profile.split('.')[0] # Trim extension if someone added it
profile_path = os.path.join(os.path.dirname(__file__), 'profiles', profile + '.yml')
else:
profile_path = profile
if os.path.exists(profile_path):
try:
rendered_template = _render_profile(profile_path, caller, runner)
line = '-' * 80
log.debug('\n%s\n%s\n%s\n', line, rendered_template, line)
data.update(yaml.load(rendered_template))
except Exception as ex:
log.debug(ex, exc_info=True)
raise salt.exceptions.SaltException('Rendering profile failed: {}'.format(ex))
else:
raise salt.exceptions.SaltException('Profile "{}" is not found.'.format(profile))
return data | python | def get_profile(profile, caller, runner):
'''
Get profile.
:param profile:
:return:
'''
profiles = profile.split(',')
data = {}
for profile in profiles:
if os.path.basename(profile) == profile:
profile = profile.split('.')[0] # Trim extension if someone added it
profile_path = os.path.join(os.path.dirname(__file__), 'profiles', profile + '.yml')
else:
profile_path = profile
if os.path.exists(profile_path):
try:
rendered_template = _render_profile(profile_path, caller, runner)
line = '-' * 80
log.debug('\n%s\n%s\n%s\n', line, rendered_template, line)
data.update(yaml.load(rendered_template))
except Exception as ex:
log.debug(ex, exc_info=True)
raise salt.exceptions.SaltException('Rendering profile failed: {}'.format(ex))
else:
raise salt.exceptions.SaltException('Profile "{}" is not found.'.format(profile))
return data | [
"def",
"get_profile",
"(",
"profile",
",",
"caller",
",",
"runner",
")",
":",
"profiles",
"=",
"profile",
".",
"split",
"(",
"','",
")",
"data",
"=",
"{",
"}",
"for",
"profile",
"in",
"profiles",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
... | Get profile.
:param profile:
:return: | [
"Get",
"profile",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/__init__.py#L25-L52 | train |
saltstack/salt | salt/cli/support/__init__.py | get_profiles | def get_profiles(config):
'''
Get available profiles.
:return:
'''
profiles = []
for profile_name in os.listdir(os.path.join(os.path.dirname(__file__), 'profiles')):
if profile_name.endswith('.yml'):
profiles.append(profile_name.split('.')[0])
return sorted(profiles) | python | def get_profiles(config):
'''
Get available profiles.
:return:
'''
profiles = []
for profile_name in os.listdir(os.path.join(os.path.dirname(__file__), 'profiles')):
if profile_name.endswith('.yml'):
profiles.append(profile_name.split('.')[0])
return sorted(profiles) | [
"def",
"get_profiles",
"(",
"config",
")",
":",
"profiles",
"=",
"[",
"]",
"for",
"profile_name",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'profiles'",
")",
... | Get available profiles.
:return: | [
"Get",
"available",
"profiles",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/__init__.py#L55-L66 | train |
saltstack/salt | salt/utils/user.py | get_user | def get_user():
'''
Get the current user
'''
if HAS_PWD:
ret = pwd.getpwuid(os.geteuid()).pw_name
elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32:
ret = salt.utils.win_functions.get_current_user()
else:
raise CommandExecutionError(
'Required external library (pwd or win32api) not installed')
return salt.utils.stringutils.to_unicode(ret) | python | def get_user():
'''
Get the current user
'''
if HAS_PWD:
ret = pwd.getpwuid(os.geteuid()).pw_name
elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32:
ret = salt.utils.win_functions.get_current_user()
else:
raise CommandExecutionError(
'Required external library (pwd or win32api) not installed')
return salt.utils.stringutils.to_unicode(ret) | [
"def",
"get_user",
"(",
")",
":",
"if",
"HAS_PWD",
":",
"ret",
"=",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"geteuid",
"(",
")",
")",
".",
"pw_name",
"elif",
"HAS_WIN_FUNCTIONS",
"and",
"salt",
".",
"utils",
".",
"win_functions",
".",
"HAS_WIN32",
":",... | Get the current user | [
"Get",
"the",
"current",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L54-L65 | train |
saltstack/salt | salt/utils/user.py | get_uid | def get_uid(user=None):
'''
Get the uid for a given user name. If no user given, the current euid will
be returned. If the user does not exist, None will be returned. On systems
which do not support pwd or os.geteuid, None will be returned.
'''
if not HAS_PWD:
return None
elif user is None:
try:
return os.geteuid()
except AttributeError:
return None
else:
try:
return pwd.getpwnam(user).pw_uid
except KeyError:
return None | python | def get_uid(user=None):
'''
Get the uid for a given user name. If no user given, the current euid will
be returned. If the user does not exist, None will be returned. On systems
which do not support pwd or os.geteuid, None will be returned.
'''
if not HAS_PWD:
return None
elif user is None:
try:
return os.geteuid()
except AttributeError:
return None
else:
try:
return pwd.getpwnam(user).pw_uid
except KeyError:
return None | [
"def",
"get_uid",
"(",
"user",
"=",
"None",
")",
":",
"if",
"not",
"HAS_PWD",
":",
"return",
"None",
"elif",
"user",
"is",
"None",
":",
"try",
":",
"return",
"os",
".",
"geteuid",
"(",
")",
"except",
"AttributeError",
":",
"return",
"None",
"else",
"... | Get the uid for a given user name. If no user given, the current euid will
be returned. If the user does not exist, None will be returned. On systems
which do not support pwd or os.geteuid, None will be returned. | [
"Get",
"the",
"uid",
"for",
"a",
"given",
"user",
"name",
".",
"If",
"no",
"user",
"given",
"the",
"current",
"euid",
"will",
"be",
"returned",
".",
"If",
"the",
"user",
"does",
"not",
"exist",
"None",
"will",
"be",
"returned",
".",
"On",
"systems",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L69-L86 | train |
saltstack/salt | salt/utils/user.py | _win_user_token_is_admin | def _win_user_token_is_admin(user_token):
'''
Using the win32 api, determine if the user with token 'user_token' has
administrator rights.
See MSDN entry here:
http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx
'''
class SID_IDENTIFIER_AUTHORITY(ctypes.Structure):
_fields_ = [
("byte0", ctypes.c_byte),
("byte1", ctypes.c_byte),
("byte2", ctypes.c_byte),
("byte3", ctypes.c_byte),
("byte4", ctypes.c_byte),
("byte5", ctypes.c_byte),
]
nt_authority = SID_IDENTIFIER_AUTHORITY()
nt_authority.byte5 = 5
SECURITY_BUILTIN_DOMAIN_RID = 0x20
DOMAIN_ALIAS_RID_ADMINS = 0x220
administrators_group = ctypes.c_void_p()
if ctypes.windll.advapi32.AllocateAndInitializeSid(
ctypes.byref(nt_authority),
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
ctypes.byref(administrators_group)) == 0:
raise Exception("AllocateAndInitializeSid failed")
try:
is_admin = ctypes.wintypes.BOOL()
if ctypes.windll.advapi32.CheckTokenMembership(
user_token,
administrators_group,
ctypes.byref(is_admin)) == 0:
raise Exception("CheckTokenMembership failed")
return is_admin.value != 0
finally:
ctypes.windll.advapi32.FreeSid(administrators_group) | python | def _win_user_token_is_admin(user_token):
'''
Using the win32 api, determine if the user with token 'user_token' has
administrator rights.
See MSDN entry here:
http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx
'''
class SID_IDENTIFIER_AUTHORITY(ctypes.Structure):
_fields_ = [
("byte0", ctypes.c_byte),
("byte1", ctypes.c_byte),
("byte2", ctypes.c_byte),
("byte3", ctypes.c_byte),
("byte4", ctypes.c_byte),
("byte5", ctypes.c_byte),
]
nt_authority = SID_IDENTIFIER_AUTHORITY()
nt_authority.byte5 = 5
SECURITY_BUILTIN_DOMAIN_RID = 0x20
DOMAIN_ALIAS_RID_ADMINS = 0x220
administrators_group = ctypes.c_void_p()
if ctypes.windll.advapi32.AllocateAndInitializeSid(
ctypes.byref(nt_authority),
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
ctypes.byref(administrators_group)) == 0:
raise Exception("AllocateAndInitializeSid failed")
try:
is_admin = ctypes.wintypes.BOOL()
if ctypes.windll.advapi32.CheckTokenMembership(
user_token,
administrators_group,
ctypes.byref(is_admin)) == 0:
raise Exception("CheckTokenMembership failed")
return is_admin.value != 0
finally:
ctypes.windll.advapi32.FreeSid(administrators_group) | [
"def",
"_win_user_token_is_admin",
"(",
"user_token",
")",
":",
"class",
"SID_IDENTIFIER_AUTHORITY",
"(",
"ctypes",
".",
"Structure",
")",
":",
"_fields_",
"=",
"[",
"(",
"\"byte0\"",
",",
"ctypes",
".",
"c_byte",
")",
",",
"(",
"\"byte1\"",
",",
"ctypes",
"... | Using the win32 api, determine if the user with token 'user_token' has
administrator rights.
See MSDN entry here:
http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx | [
"Using",
"the",
"win32",
"api",
"determine",
"if",
"the",
"user",
"with",
"token",
"user_token",
"has",
"administrator",
"rights",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L89-L131 | train |
saltstack/salt | salt/utils/user.py | get_specific_user | def get_specific_user():
'''
Get a user name for publishing. If you find the user is "root" attempt to be
more specific
'''
user = get_user()
if salt.utils.platform.is_windows():
if _win_current_user_is_admin():
return 'sudo_{0}'.format(user)
else:
env_vars = ('SUDO_USER',)
if user == 'root':
for evar in env_vars:
if evar in os.environ:
return 'sudo_{0}'.format(os.environ[evar])
return user | python | def get_specific_user():
'''
Get a user name for publishing. If you find the user is "root" attempt to be
more specific
'''
user = get_user()
if salt.utils.platform.is_windows():
if _win_current_user_is_admin():
return 'sudo_{0}'.format(user)
else:
env_vars = ('SUDO_USER',)
if user == 'root':
for evar in env_vars:
if evar in os.environ:
return 'sudo_{0}'.format(os.environ[evar])
return user | [
"def",
"get_specific_user",
"(",
")",
":",
"user",
"=",
"get_user",
"(",
")",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"if",
"_win_current_user_is_admin",
"(",
")",
":",
"return",
"'sudo_{0}'",
".",
"format",
"(",
"u... | Get a user name for publishing. If you find the user is "root" attempt to be
more specific | [
"Get",
"a",
"user",
"name",
"for",
"publishing",
".",
"If",
"you",
"find",
"the",
"user",
"is",
"root",
"attempt",
"to",
"be",
"more",
"specific"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L142-L157 | train |
saltstack/salt | salt/utils/user.py | chugid | def chugid(runas, group=None):
'''
Change the current process to belong to the specified user (and the groups
to which it belongs)
'''
uinfo = pwd.getpwnam(runas)
supgroups = []
supgroups_seen = set()
if group:
try:
target_pw_gid = grp.getgrnam(group).gr_gid
except KeyError as err:
raise CommandExecutionError(
'Failed to fetch the GID for {0}. Error: {1}'.format(
group, err
)
)
else:
target_pw_gid = uinfo.pw_gid
# The line below used to exclude the current user's primary gid.
# However, when root belongs to more than one group
# this causes root's primary group of '0' to be dropped from
# his grouplist. On FreeBSD, at least, this makes some
# command executions fail with 'access denied'.
#
# The Python documentation says that os.setgroups sets only
# the supplemental groups for a running process. On FreeBSD
# this does not appear to be strictly true.
group_list = get_group_dict(runas, include_default=True)
if sys.platform == 'darwin':
group_list = dict((k, v) for k, v in six.iteritems(group_list)
if not k.startswith('_'))
for group_name in group_list:
gid = group_list[group_name]
if (gid not in supgroups_seen
and not supgroups_seen.add(gid)):
supgroups.append(gid)
if os.getgid() != target_pw_gid:
try:
os.setgid(target_pw_gid)
except OSError as err:
raise CommandExecutionError(
'Failed to change from gid {0} to {1}. Error: {2}'.format(
os.getgid(), target_pw_gid, err
)
)
# Set supplemental groups
if sorted(os.getgroups()) != sorted(supgroups):
try:
os.setgroups(supgroups)
except OSError as err:
raise CommandExecutionError(
'Failed to set supplemental groups to {0}. Error: {1}'.format(
supgroups, err
)
)
if os.getuid() != uinfo.pw_uid:
try:
os.setuid(uinfo.pw_uid)
except OSError as err:
raise CommandExecutionError(
'Failed to change from uid {0} to {1}. Error: {2}'.format(
os.getuid(), uinfo.pw_uid, err
)
) | python | def chugid(runas, group=None):
'''
Change the current process to belong to the specified user (and the groups
to which it belongs)
'''
uinfo = pwd.getpwnam(runas)
supgroups = []
supgroups_seen = set()
if group:
try:
target_pw_gid = grp.getgrnam(group).gr_gid
except KeyError as err:
raise CommandExecutionError(
'Failed to fetch the GID for {0}. Error: {1}'.format(
group, err
)
)
else:
target_pw_gid = uinfo.pw_gid
# The line below used to exclude the current user's primary gid.
# However, when root belongs to more than one group
# this causes root's primary group of '0' to be dropped from
# his grouplist. On FreeBSD, at least, this makes some
# command executions fail with 'access denied'.
#
# The Python documentation says that os.setgroups sets only
# the supplemental groups for a running process. On FreeBSD
# this does not appear to be strictly true.
group_list = get_group_dict(runas, include_default=True)
if sys.platform == 'darwin':
group_list = dict((k, v) for k, v in six.iteritems(group_list)
if not k.startswith('_'))
for group_name in group_list:
gid = group_list[group_name]
if (gid not in supgroups_seen
and not supgroups_seen.add(gid)):
supgroups.append(gid)
if os.getgid() != target_pw_gid:
try:
os.setgid(target_pw_gid)
except OSError as err:
raise CommandExecutionError(
'Failed to change from gid {0} to {1}. Error: {2}'.format(
os.getgid(), target_pw_gid, err
)
)
# Set supplemental groups
if sorted(os.getgroups()) != sorted(supgroups):
try:
os.setgroups(supgroups)
except OSError as err:
raise CommandExecutionError(
'Failed to set supplemental groups to {0}. Error: {1}'.format(
supgroups, err
)
)
if os.getuid() != uinfo.pw_uid:
try:
os.setuid(uinfo.pw_uid)
except OSError as err:
raise CommandExecutionError(
'Failed to change from uid {0} to {1}. Error: {2}'.format(
os.getuid(), uinfo.pw_uid, err
)
) | [
"def",
"chugid",
"(",
"runas",
",",
"group",
"=",
"None",
")",
":",
"uinfo",
"=",
"pwd",
".",
"getpwnam",
"(",
"runas",
")",
"supgroups",
"=",
"[",
"]",
"supgroups_seen",
"=",
"set",
"(",
")",
"if",
"group",
":",
"try",
":",
"target_pw_gid",
"=",
"... | Change the current process to belong to the specified user (and the groups
to which it belongs) | [
"Change",
"the",
"current",
"process",
"to",
"belong",
"to",
"the",
"specified",
"user",
"(",
"and",
"the",
"groups",
"to",
"which",
"it",
"belongs",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L160-L229 | train |
saltstack/salt | salt/utils/user.py | chugid_and_umask | def chugid_and_umask(runas, umask, group=None):
'''
Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process.
'''
set_runas = False
set_grp = False
current_user = getpass.getuser()
if runas and runas != current_user:
set_runas = True
runas_user = runas
else:
runas_user = current_user
current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name
if group and group != current_grp:
set_grp = True
runas_grp = group
else:
runas_grp = current_grp
if set_runas or set_grp:
chugid(runas_user, runas_grp)
if umask is not None:
os.umask(umask) | python | def chugid_and_umask(runas, umask, group=None):
'''
Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process.
'''
set_runas = False
set_grp = False
current_user = getpass.getuser()
if runas and runas != current_user:
set_runas = True
runas_user = runas
else:
runas_user = current_user
current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name
if group and group != current_grp:
set_grp = True
runas_grp = group
else:
runas_grp = current_grp
if set_runas or set_grp:
chugid(runas_user, runas_grp)
if umask is not None:
os.umask(umask) | [
"def",
"chugid_and_umask",
"(",
"runas",
",",
"umask",
",",
"group",
"=",
"None",
")",
":",
"set_runas",
"=",
"False",
"set_grp",
"=",
"False",
"current_user",
"=",
"getpass",
".",
"getuser",
"(",
")",
"if",
"runas",
"and",
"runas",
"!=",
"current_user",
... | Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process. | [
"Helper",
"method",
"for",
"for",
"subprocess",
".",
"Popen",
"to",
"initialise",
"uid",
"/",
"gid",
"and",
"umask",
"for",
"the",
"new",
"process",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L232-L257 | train |
saltstack/salt | salt/utils/user.py | get_default_group | def get_default_group(user):
'''
Returns the specified user's default group. If the user doesn't exist, a
KeyError will be raised.
'''
return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \
if HAS_GRP and HAS_PWD \
else None | python | def get_default_group(user):
'''
Returns the specified user's default group. If the user doesn't exist, a
KeyError will be raised.
'''
return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \
if HAS_GRP and HAS_PWD \
else None | [
"def",
"get_default_group",
"(",
"user",
")",
":",
"return",
"grp",
".",
"getgrgid",
"(",
"pwd",
".",
"getpwnam",
"(",
"user",
")",
".",
"pw_gid",
")",
".",
"gr_name",
"if",
"HAS_GRP",
"and",
"HAS_PWD",
"else",
"None"
] | Returns the specified user's default group. If the user doesn't exist, a
KeyError will be raised. | [
"Returns",
"the",
"specified",
"user",
"s",
"default",
"group",
".",
"If",
"the",
"user",
"doesn",
"t",
"exist",
"a",
"KeyError",
"will",
"be",
"raised",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L260-L267 | train |
saltstack/salt | salt/utils/user.py | get_group_list | def get_group_list(user, include_default=True):
'''
Returns a list of all of the system group names of which the user
is a member.
'''
if HAS_GRP is False or HAS_PWD is False:
return []
group_names = None
ugroups = set()
if hasattr(os, 'getgrouplist'):
# Try os.getgrouplist, available in python >= 3.3
log.trace('Trying os.getgrouplist for \'%s\'', user)
try:
group_names = [
grp.getgrgid(grpid).gr_name for grpid in
os.getgrouplist(user, pwd.getpwnam(user).pw_gid)
]
except Exception:
pass
elif HAS_PYSSS:
# Try pysss.getgrouplist
log.trace('Trying pysss.getgrouplist for \'%s\'', user)
try:
group_names = list(pysss.getgrouplist(user))
except Exception:
pass
if group_names is None:
# Fall back to generic code
# Include the user's default group to match behavior of
# os.getgrouplist() and pysss.getgrouplist()
log.trace('Trying generic group list for \'%s\'', user)
group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]
try:
default_group = get_default_group(user)
if default_group not in group_names:
group_names.append(default_group)
except KeyError:
# If for some reason the user does not have a default group
pass
if group_names is not None:
ugroups.update(group_names)
if include_default is False:
# Historically, saltstack code for getting group lists did not
# include the default group. Some things may only want
# supplemental groups, so include_default=False omits the users
# default group.
try:
default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name
ugroups.remove(default_group)
except KeyError:
# If for some reason the user does not have a default group
pass
log.trace('Group list for user \'%s\': %s', user, sorted(ugroups))
return sorted(ugroups) | python | def get_group_list(user, include_default=True):
'''
Returns a list of all of the system group names of which the user
is a member.
'''
if HAS_GRP is False or HAS_PWD is False:
return []
group_names = None
ugroups = set()
if hasattr(os, 'getgrouplist'):
# Try os.getgrouplist, available in python >= 3.3
log.trace('Trying os.getgrouplist for \'%s\'', user)
try:
group_names = [
grp.getgrgid(grpid).gr_name for grpid in
os.getgrouplist(user, pwd.getpwnam(user).pw_gid)
]
except Exception:
pass
elif HAS_PYSSS:
# Try pysss.getgrouplist
log.trace('Trying pysss.getgrouplist for \'%s\'', user)
try:
group_names = list(pysss.getgrouplist(user))
except Exception:
pass
if group_names is None:
# Fall back to generic code
# Include the user's default group to match behavior of
# os.getgrouplist() and pysss.getgrouplist()
log.trace('Trying generic group list for \'%s\'', user)
group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]
try:
default_group = get_default_group(user)
if default_group not in group_names:
group_names.append(default_group)
except KeyError:
# If for some reason the user does not have a default group
pass
if group_names is not None:
ugroups.update(group_names)
if include_default is False:
# Historically, saltstack code for getting group lists did not
# include the default group. Some things may only want
# supplemental groups, so include_default=False omits the users
# default group.
try:
default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name
ugroups.remove(default_group)
except KeyError:
# If for some reason the user does not have a default group
pass
log.trace('Group list for user \'%s\': %s', user, sorted(ugroups))
return sorted(ugroups) | [
"def",
"get_group_list",
"(",
"user",
",",
"include_default",
"=",
"True",
")",
":",
"if",
"HAS_GRP",
"is",
"False",
"or",
"HAS_PWD",
"is",
"False",
":",
"return",
"[",
"]",
"group_names",
"=",
"None",
"ugroups",
"=",
"set",
"(",
")",
"if",
"hasattr",
... | Returns a list of all of the system group names of which the user
is a member. | [
"Returns",
"a",
"list",
"of",
"all",
"of",
"the",
"system",
"group",
"names",
"of",
"which",
"the",
"user",
"is",
"a",
"member",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L270-L326 | train |
saltstack/salt | salt/utils/user.py | get_group_dict | def get_group_dict(user=None, include_default=True):
'''
Returns a dict of all of the system groups as keys, and group ids
as values, of which the user is a member.
E.g.: {'staff': 501, 'sudo': 27}
'''
if HAS_GRP is False or HAS_PWD is False:
return {}
group_dict = {}
group_names = get_group_list(user, include_default=include_default)
for group in group_names:
group_dict.update({group: grp.getgrnam(group).gr_gid})
return group_dict | python | def get_group_dict(user=None, include_default=True):
'''
Returns a dict of all of the system groups as keys, and group ids
as values, of which the user is a member.
E.g.: {'staff': 501, 'sudo': 27}
'''
if HAS_GRP is False or HAS_PWD is False:
return {}
group_dict = {}
group_names = get_group_list(user, include_default=include_default)
for group in group_names:
group_dict.update({group: grp.getgrnam(group).gr_gid})
return group_dict | [
"def",
"get_group_dict",
"(",
"user",
"=",
"None",
",",
"include_default",
"=",
"True",
")",
":",
"if",
"HAS_GRP",
"is",
"False",
"or",
"HAS_PWD",
"is",
"False",
":",
"return",
"{",
"}",
"group_dict",
"=",
"{",
"}",
"group_names",
"=",
"get_group_list",
... | Returns a dict of all of the system groups as keys, and group ids
as values, of which the user is a member.
E.g.: {'staff': 501, 'sudo': 27} | [
"Returns",
"a",
"dict",
"of",
"all",
"of",
"the",
"system",
"groups",
"as",
"keys",
"and",
"group",
"ids",
"as",
"values",
"of",
"which",
"the",
"user",
"is",
"a",
"member",
".",
"E",
".",
"g",
".",
":",
"{",
"staff",
":",
"501",
"sudo",
":",
"27... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L329-L341 | train |
saltstack/salt | salt/utils/user.py | get_gid_list | def get_gid_list(user, include_default=True):
'''
Returns a list of all of the system group IDs of which the user
is a member.
'''
if HAS_GRP is False or HAS_PWD is False:
return []
gid_list = list(
six.itervalues(
get_group_dict(user, include_default=include_default)
)
)
return sorted(set(gid_list)) | python | def get_gid_list(user, include_default=True):
'''
Returns a list of all of the system group IDs of which the user
is a member.
'''
if HAS_GRP is False or HAS_PWD is False:
return []
gid_list = list(
six.itervalues(
get_group_dict(user, include_default=include_default)
)
)
return sorted(set(gid_list)) | [
"def",
"get_gid_list",
"(",
"user",
",",
"include_default",
"=",
"True",
")",
":",
"if",
"HAS_GRP",
"is",
"False",
"or",
"HAS_PWD",
"is",
"False",
":",
"return",
"[",
"]",
"gid_list",
"=",
"list",
"(",
"six",
".",
"itervalues",
"(",
"get_group_dict",
"("... | Returns a list of all of the system group IDs of which the user
is a member. | [
"Returns",
"a",
"list",
"of",
"all",
"of",
"the",
"system",
"group",
"IDs",
"of",
"which",
"the",
"user",
"is",
"a",
"member",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L344-L356 | train |
saltstack/salt | salt/utils/user.py | get_gid | def get_gid(group=None):
'''
Get the gid for a given group name. If no group given, the current egid
will be returned. If the group does not exist, None will be returned. On
systems which do not support grp or os.getegid it will return None.
'''
if not HAS_GRP:
return None
if group is None:
try:
return os.getegid()
except AttributeError:
return None
else:
try:
return grp.getgrnam(group).gr_gid
except KeyError:
return None | python | def get_gid(group=None):
'''
Get the gid for a given group name. If no group given, the current egid
will be returned. If the group does not exist, None will be returned. On
systems which do not support grp or os.getegid it will return None.
'''
if not HAS_GRP:
return None
if group is None:
try:
return os.getegid()
except AttributeError:
return None
else:
try:
return grp.getgrnam(group).gr_gid
except KeyError:
return None | [
"def",
"get_gid",
"(",
"group",
"=",
"None",
")",
":",
"if",
"not",
"HAS_GRP",
":",
"return",
"None",
"if",
"group",
"is",
"None",
":",
"try",
":",
"return",
"os",
".",
"getegid",
"(",
")",
"except",
"AttributeError",
":",
"return",
"None",
"else",
"... | Get the gid for a given group name. If no group given, the current egid
will be returned. If the group does not exist, None will be returned. On
systems which do not support grp or os.getegid it will return None. | [
"Get",
"the",
"gid",
"for",
"a",
"given",
"group",
"name",
".",
"If",
"no",
"group",
"given",
"the",
"current",
"egid",
"will",
"be",
"returned",
".",
"If",
"the",
"group",
"does",
"not",
"exist",
"None",
"will",
"be",
"returned",
".",
"On",
"systems",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L359-L376 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | html_override_tool | def html_override_tool():
'''
Bypass the normal handler and serve HTML for all URLs
The ``app_path`` setting must be non-empty and the request must ask for
``text/html`` in the ``Accept`` header.
'''
apiopts = cherrypy.config['apiopts']
request = cherrypy.request
url_blacklist = (
apiopts.get('app_path', '/app'),
apiopts.get('static_path', '/static'),
)
if 'app' not in cherrypy.config['apiopts']:
return
if request.path_info.startswith(url_blacklist):
return
if request.headers.get('Accept') == '*/*':
return
try:
wants_html = cherrypy.lib.cptools.accept('text/html')
except cherrypy.HTTPError:
return
else:
if wants_html != 'text/html':
return
raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) | python | def html_override_tool():
'''
Bypass the normal handler and serve HTML for all URLs
The ``app_path`` setting must be non-empty and the request must ask for
``text/html`` in the ``Accept`` header.
'''
apiopts = cherrypy.config['apiopts']
request = cherrypy.request
url_blacklist = (
apiopts.get('app_path', '/app'),
apiopts.get('static_path', '/static'),
)
if 'app' not in cherrypy.config['apiopts']:
return
if request.path_info.startswith(url_blacklist):
return
if request.headers.get('Accept') == '*/*':
return
try:
wants_html = cherrypy.lib.cptools.accept('text/html')
except cherrypy.HTTPError:
return
else:
if wants_html != 'text/html':
return
raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) | [
"def",
"html_override_tool",
"(",
")",
":",
"apiopts",
"=",
"cherrypy",
".",
"config",
"[",
"'apiopts'",
"]",
"request",
"=",
"cherrypy",
".",
"request",
"url_blacklist",
"=",
"(",
"apiopts",
".",
"get",
"(",
"'app_path'",
",",
"'/app'",
")",
",",
"apiopts... | Bypass the normal handler and serve HTML for all URLs
The ``app_path`` setting must be non-empty and the request must ask for
``text/html`` in the ``Accept`` header. | [
"Bypass",
"the",
"normal",
"handler",
"and",
"serve",
"HTML",
"for",
"all",
"URLs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L649-L681 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | salt_token_tool | def salt_token_tool():
'''
If the custom authentication header is supplied, put it in the cookie dict
so the rest of the session-based auth works as intended
'''
x_auth = cherrypy.request.headers.get('X-Auth-Token', None)
# X-Auth-Token header trumps session cookie
if x_auth:
cherrypy.request.cookie['session_id'] = x_auth | python | def salt_token_tool():
'''
If the custom authentication header is supplied, put it in the cookie dict
so the rest of the session-based auth works as intended
'''
x_auth = cherrypy.request.headers.get('X-Auth-Token', None)
# X-Auth-Token header trumps session cookie
if x_auth:
cherrypy.request.cookie['session_id'] = x_auth | [
"def",
"salt_token_tool",
"(",
")",
":",
"x_auth",
"=",
"cherrypy",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'X-Auth-Token'",
",",
"None",
")",
"# X-Auth-Token header trumps session cookie",
"if",
"x_auth",
":",
"cherrypy",
".",
"request",
".",
"cookie"... | If the custom authentication header is supplied, put it in the cookie dict
so the rest of the session-based auth works as intended | [
"If",
"the",
"custom",
"authentication",
"header",
"is",
"supplied",
"put",
"it",
"in",
"the",
"cookie",
"dict",
"so",
"the",
"rest",
"of",
"the",
"session",
"-",
"based",
"auth",
"works",
"as",
"intended"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L684-L693 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | salt_api_acl_tool | def salt_api_acl_tool(username, request):
'''
..versionadded:: 2016.3.0
Verifies user requests against the API whitelist. (User/IP pair)
in order to provide whitelisting for the API similar to the
master, but over the API.
..code-block:: yaml
rest_cherrypy:
api_acl:
users:
'*':
- 1.1.1.1
- 1.1.1.2
foo:
- 8.8.4.4
bar:
- '*'
:param username: Username to check against the API.
:type username: str
:param request: Cherrypy request to check against the API.
:type request: cherrypy.request
'''
failure_str = ("[api_acl] Authentication failed for "
"user %s from IP %s")
success_str = ("[api_acl] Authentication sucessful for "
"user %s from IP %s")
pass_str = ("[api_acl] Authentication not checked for "
"user %s from IP %s")
acl = None
# Salt Configuration
salt_config = cherrypy.config.get('saltopts', None)
if salt_config:
# Cherrypy Config.
cherrypy_conf = salt_config.get('rest_cherrypy', None)
if cherrypy_conf:
# ACL Config.
acl = cherrypy_conf.get('api_acl', None)
ip = request.remote.ip
if acl:
users = acl.get('users', {})
if users:
if username in users:
if ip in users[username] or '*' in users[username]:
logger.info(success_str, username, ip)
return True
else:
logger.info(failure_str, username, ip)
return False
elif username not in users and '*' in users:
if ip in users['*'] or '*' in users['*']:
logger.info(success_str, username, ip)
return True
else:
logger.info(failure_str, username, ip)
return False
else:
logger.info(failure_str, username, ip)
return False
else:
logger.info(pass_str, username, ip)
return True | python | def salt_api_acl_tool(username, request):
'''
..versionadded:: 2016.3.0
Verifies user requests against the API whitelist. (User/IP pair)
in order to provide whitelisting for the API similar to the
master, but over the API.
..code-block:: yaml
rest_cherrypy:
api_acl:
users:
'*':
- 1.1.1.1
- 1.1.1.2
foo:
- 8.8.4.4
bar:
- '*'
:param username: Username to check against the API.
:type username: str
:param request: Cherrypy request to check against the API.
:type request: cherrypy.request
'''
failure_str = ("[api_acl] Authentication failed for "
"user %s from IP %s")
success_str = ("[api_acl] Authentication sucessful for "
"user %s from IP %s")
pass_str = ("[api_acl] Authentication not checked for "
"user %s from IP %s")
acl = None
# Salt Configuration
salt_config = cherrypy.config.get('saltopts', None)
if salt_config:
# Cherrypy Config.
cherrypy_conf = salt_config.get('rest_cherrypy', None)
if cherrypy_conf:
# ACL Config.
acl = cherrypy_conf.get('api_acl', None)
ip = request.remote.ip
if acl:
users = acl.get('users', {})
if users:
if username in users:
if ip in users[username] or '*' in users[username]:
logger.info(success_str, username, ip)
return True
else:
logger.info(failure_str, username, ip)
return False
elif username not in users and '*' in users:
if ip in users['*'] or '*' in users['*']:
logger.info(success_str, username, ip)
return True
else:
logger.info(failure_str, username, ip)
return False
else:
logger.info(failure_str, username, ip)
return False
else:
logger.info(pass_str, username, ip)
return True | [
"def",
"salt_api_acl_tool",
"(",
"username",
",",
"request",
")",
":",
"failure_str",
"=",
"(",
"\"[api_acl] Authentication failed for \"",
"\"user %s from IP %s\"",
")",
"success_str",
"=",
"(",
"\"[api_acl] Authentication sucessful for \"",
"\"user %s from IP %s\"",
")",
"p... | ..versionadded:: 2016.3.0
Verifies user requests against the API whitelist. (User/IP pair)
in order to provide whitelisting for the API similar to the
master, but over the API.
..code-block:: yaml
rest_cherrypy:
api_acl:
users:
'*':
- 1.1.1.1
- 1.1.1.2
foo:
- 8.8.4.4
bar:
- '*'
:param username: Username to check against the API.
:type username: str
:param request: Cherrypy request to check against the API.
:type request: cherrypy.request | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L696-L762 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | salt_ip_verify_tool | def salt_ip_verify_tool():
'''
If there is a list of restricted IPs, verify current
client is coming from one of those IPs.
'''
# This is overly cumbersome and crude,
# But, it's also safe... ish...
salt_config = cherrypy.config.get('saltopts', None)
if salt_config:
cherrypy_conf = salt_config.get('rest_cherrypy', None)
if cherrypy_conf:
auth_ip_list = cherrypy_conf.get('authorized_ips', None)
if auth_ip_list:
logger.debug('Found IP list: %s', auth_ip_list)
rem_ip = cherrypy.request.headers.get('Remote-Addr', None)
logger.debug('Request from IP: %s', rem_ip)
if rem_ip not in auth_ip_list:
logger.error('Blocked IP: %s', rem_ip)
raise cherrypy.HTTPError(403, 'Bad IP') | python | def salt_ip_verify_tool():
'''
If there is a list of restricted IPs, verify current
client is coming from one of those IPs.
'''
# This is overly cumbersome and crude,
# But, it's also safe... ish...
salt_config = cherrypy.config.get('saltopts', None)
if salt_config:
cherrypy_conf = salt_config.get('rest_cherrypy', None)
if cherrypy_conf:
auth_ip_list = cherrypy_conf.get('authorized_ips', None)
if auth_ip_list:
logger.debug('Found IP list: %s', auth_ip_list)
rem_ip = cherrypy.request.headers.get('Remote-Addr', None)
logger.debug('Request from IP: %s', rem_ip)
if rem_ip not in auth_ip_list:
logger.error('Blocked IP: %s', rem_ip)
raise cherrypy.HTTPError(403, 'Bad IP') | [
"def",
"salt_ip_verify_tool",
"(",
")",
":",
"# This is overly cumbersome and crude,",
"# But, it's also safe... ish...",
"salt_config",
"=",
"cherrypy",
".",
"config",
".",
"get",
"(",
"'saltopts'",
",",
"None",
")",
"if",
"salt_config",
":",
"cherrypy_conf",
"=",
"s... | If there is a list of restricted IPs, verify current
client is coming from one of those IPs. | [
"If",
"there",
"is",
"a",
"list",
"of",
"restricted",
"IPs",
"verify",
"current",
"client",
"is",
"coming",
"from",
"one",
"of",
"those",
"IPs",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L765-L783 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | cors_tool | def cors_tool():
'''
Handle both simple and complex CORS requests
Add CORS headers to each response. If the request is a CORS preflight
request swap out the default handler with a simple, single-purpose handler
that verifies the request and provides a valid CORS response.
'''
req_head = cherrypy.request.headers
resp_head = cherrypy.response.headers
# Always set response headers necessary for 'simple' CORS.
resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*')
resp_head['Access-Control-Expose-Headers'] = 'GET, POST'
resp_head['Access-Control-Allow-Credentials'] = 'true'
# Non-simple CORS preflight request; short-circuit the normal handler.
if cherrypy.request.method == 'OPTIONS':
ac_method = req_head.get('Access-Control-Request-Method', None)
allowed_methods = ['GET', 'POST']
allowed_headers = [
'Content-Type',
'X-Auth-Token',
'X-Requested-With',
]
if ac_method and ac_method in allowed_methods:
resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods)
resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers)
resp_head['Connection'] = 'keep-alive'
resp_head['Access-Control-Max-Age'] = '1400'
# CORS requests should short-circuit the other tools.
cherrypy.response.body = ''
cherrypy.response.status = 200
cherrypy.serving.request.handler = None
# Needed to avoid the auth_tool check.
if cherrypy.request.config.get('tools.sessions.on', False):
cherrypy.session['token'] = True
return True | python | def cors_tool():
'''
Handle both simple and complex CORS requests
Add CORS headers to each response. If the request is a CORS preflight
request swap out the default handler with a simple, single-purpose handler
that verifies the request and provides a valid CORS response.
'''
req_head = cherrypy.request.headers
resp_head = cherrypy.response.headers
# Always set response headers necessary for 'simple' CORS.
resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*')
resp_head['Access-Control-Expose-Headers'] = 'GET, POST'
resp_head['Access-Control-Allow-Credentials'] = 'true'
# Non-simple CORS preflight request; short-circuit the normal handler.
if cherrypy.request.method == 'OPTIONS':
ac_method = req_head.get('Access-Control-Request-Method', None)
allowed_methods = ['GET', 'POST']
allowed_headers = [
'Content-Type',
'X-Auth-Token',
'X-Requested-With',
]
if ac_method and ac_method in allowed_methods:
resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods)
resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers)
resp_head['Connection'] = 'keep-alive'
resp_head['Access-Control-Max-Age'] = '1400'
# CORS requests should short-circuit the other tools.
cherrypy.response.body = ''
cherrypy.response.status = 200
cherrypy.serving.request.handler = None
# Needed to avoid the auth_tool check.
if cherrypy.request.config.get('tools.sessions.on', False):
cherrypy.session['token'] = True
return True | [
"def",
"cors_tool",
"(",
")",
":",
"req_head",
"=",
"cherrypy",
".",
"request",
".",
"headers",
"resp_head",
"=",
"cherrypy",
".",
"response",
".",
"headers",
"# Always set response headers necessary for 'simple' CORS.",
"resp_head",
"[",
"'Access-Control-Allow-Origin'",
... | Handle both simple and complex CORS requests
Add CORS headers to each response. If the request is a CORS preflight
request swap out the default handler with a simple, single-purpose handler
that verifies the request and provides a valid CORS response. | [
"Handle",
"both",
"simple",
"and",
"complex",
"CORS",
"requests"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L798-L840 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | hypermedia_handler | def hypermedia_handler(*args, **kwargs):
'''
Determine the best output format based on the Accept header, execute the
regular handler, and transform the output to the request content type (even
if it's an error).
:param args: Pass args through to the main handler
:param kwargs: Pass kwargs through to the main handler
'''
# Execute the real handler. Handle or pass-through any errors we know how
# to handle (auth & HTTP errors). Reformat any errors we don't know how to
# handle as a data structure.
try:
cherrypy.response.processors = dict(ct_out_map)
ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs)
except (salt.exceptions.AuthenticationError,
salt.exceptions.AuthorizationError,
salt.exceptions.EauthAuthenticationError,
salt.exceptions.TokenAuthenticationError):
raise cherrypy.HTTPError(401)
except salt.exceptions.SaltInvocationError:
raise cherrypy.HTTPError(400)
except (salt.exceptions.SaltDaemonNotRunning,
salt.exceptions.SaltReqTimeoutError) as exc:
raise cherrypy.HTTPError(503, exc.strerror)
except salt.exceptions.SaltClientTimeout:
raise cherrypy.HTTPError(504)
except cherrypy.CherryPyException:
raise
except Exception as exc:
# The TimeoutError exception class was removed in CherryPy in 12.0.0, but
# Still check existence of TimeoutError and handle in CherryPy < 12.
# The check was moved down from the SaltClientTimeout error line because
# A one-line if statement throws a BaseException inheritance TypeError.
if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError):
raise cherrypy.HTTPError(504)
import traceback
logger.debug("Error while processing request for: %s",
cherrypy.request.path_info,
exc_info=True)
cherrypy.response.status = 500
ret = {
'status': cherrypy.response.status,
'return': '{0}'.format(traceback.format_exc(exc))
if cherrypy.config['debug']
else "An unexpected error occurred"}
# Raises 406 if requested content-type is not supported
best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map])
# Transform the output from the handler into the requested output format
cherrypy.response.headers['Content-Type'] = best
out = cherrypy.response.processors[best]
try:
response = out(ret)
if six.PY3:
response = salt.utils.stringutils.to_bytes(response)
return response
except Exception:
msg = 'Could not serialize the return data from Salt.'
logger.debug(msg, exc_info=True)
raise cherrypy.HTTPError(500, msg) | python | def hypermedia_handler(*args, **kwargs):
'''
Determine the best output format based on the Accept header, execute the
regular handler, and transform the output to the request content type (even
if it's an error).
:param args: Pass args through to the main handler
:param kwargs: Pass kwargs through to the main handler
'''
# Execute the real handler. Handle or pass-through any errors we know how
# to handle (auth & HTTP errors). Reformat any errors we don't know how to
# handle as a data structure.
try:
cherrypy.response.processors = dict(ct_out_map)
ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs)
except (salt.exceptions.AuthenticationError,
salt.exceptions.AuthorizationError,
salt.exceptions.EauthAuthenticationError,
salt.exceptions.TokenAuthenticationError):
raise cherrypy.HTTPError(401)
except salt.exceptions.SaltInvocationError:
raise cherrypy.HTTPError(400)
except (salt.exceptions.SaltDaemonNotRunning,
salt.exceptions.SaltReqTimeoutError) as exc:
raise cherrypy.HTTPError(503, exc.strerror)
except salt.exceptions.SaltClientTimeout:
raise cherrypy.HTTPError(504)
except cherrypy.CherryPyException:
raise
except Exception as exc:
# The TimeoutError exception class was removed in CherryPy in 12.0.0, but
# Still check existence of TimeoutError and handle in CherryPy < 12.
# The check was moved down from the SaltClientTimeout error line because
# A one-line if statement throws a BaseException inheritance TypeError.
if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError):
raise cherrypy.HTTPError(504)
import traceback
logger.debug("Error while processing request for: %s",
cherrypy.request.path_info,
exc_info=True)
cherrypy.response.status = 500
ret = {
'status': cherrypy.response.status,
'return': '{0}'.format(traceback.format_exc(exc))
if cherrypy.config['debug']
else "An unexpected error occurred"}
# Raises 406 if requested content-type is not supported
best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map])
# Transform the output from the handler into the requested output format
cherrypy.response.headers['Content-Type'] = best
out = cherrypy.response.processors[best]
try:
response = out(ret)
if six.PY3:
response = salt.utils.stringutils.to_bytes(response)
return response
except Exception:
msg = 'Could not serialize the return data from Salt.'
logger.debug(msg, exc_info=True)
raise cherrypy.HTTPError(500, msg) | [
"def",
"hypermedia_handler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Execute the real handler. Handle or pass-through any errors we know how",
"# to handle (auth & HTTP errors). Reformat any errors we don't know how to",
"# handle as a data structure.",
"try",
":",
"c... | Determine the best output format based on the Accept header, execute the
regular handler, and transform the output to the request content type (even
if it's an error).
:param args: Pass args through to the main handler
:param kwargs: Pass kwargs through to the main handler | [
"Determine",
"the",
"best",
"output",
"format",
"based",
"on",
"the",
"Accept",
"header",
"execute",
"the",
"regular",
"handler",
"and",
"transform",
"the",
"output",
"to",
"the",
"request",
"content",
"type",
"(",
"even",
"if",
"it",
"s",
"an",
"error",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L853-L918 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | hypermedia_out | def hypermedia_out():
'''
Determine the best handler for the requested content type
Wrap the normal handler and transform the output from that handler into the
requested content type
'''
request = cherrypy.serving.request
request._hypermedia_inner_handler = request.handler
# If handler has been explicitly set to None, don't override.
if request.handler is not None:
request.handler = hypermedia_handler | python | def hypermedia_out():
'''
Determine the best handler for the requested content type
Wrap the normal handler and transform the output from that handler into the
requested content type
'''
request = cherrypy.serving.request
request._hypermedia_inner_handler = request.handler
# If handler has been explicitly set to None, don't override.
if request.handler is not None:
request.handler = hypermedia_handler | [
"def",
"hypermedia_out",
"(",
")",
":",
"request",
"=",
"cherrypy",
".",
"serving",
".",
"request",
"request",
".",
"_hypermedia_inner_handler",
"=",
"request",
".",
"handler",
"# If handler has been explicitly set to None, don't override.",
"if",
"request",
".",
"handl... | Determine the best handler for the requested content type
Wrap the normal handler and transform the output from that handler into the
requested content type | [
"Determine",
"the",
"best",
"handler",
"for",
"the",
"requested",
"content",
"type"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L921-L933 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | process_request_body | def process_request_body(fn):
'''
A decorator to skip a processor function if process_request_body is False
'''
@functools.wraps(fn)
def wrapped(*args, **kwargs): # pylint: disable=C0111
if cherrypy.request.process_request_body is not False:
fn(*args, **kwargs)
return wrapped | python | def process_request_body(fn):
'''
A decorator to skip a processor function if process_request_body is False
'''
@functools.wraps(fn)
def wrapped(*args, **kwargs): # pylint: disable=C0111
if cherrypy.request.process_request_body is not False:
fn(*args, **kwargs)
return wrapped | [
"def",
"process_request_body",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0111",
"if",
"cherrypy",
".",
"request",
".",
"process_request_bo... | A decorator to skip a processor function if process_request_body is False | [
"A",
"decorator",
"to",
"skip",
"a",
"processor",
"function",
"if",
"process_request_body",
"is",
"False"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L936-L944 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | urlencoded_processor | def urlencoded_processor(entity):
'''
Accept x-www-form-urlencoded data (run through CherryPy's formatter)
and reformat it into a Low State data structure.
Since we can't easily represent complicated data structures with
key-value pairs, any more complicated requirements (e.g. compound
commands) must instead be delivered via JSON or YAML.
For example::
.. code-block:: bash
curl -si localhost:8000 -d client=local -d tgt='*' \\
-d fun='test.kwarg' -d arg='one=1' -d arg='two=2'
:param entity: raw POST data
'''
# First call out to CherryPy's default processor
cherrypy._cpreqbody.process_urlencoded(entity)
cherrypy._cpreqbody.process_urlencoded(entity)
cherrypy.serving.request.unserialized_data = entity.params
cherrypy.serving.request.raw_body = '' | python | def urlencoded_processor(entity):
'''
Accept x-www-form-urlencoded data (run through CherryPy's formatter)
and reformat it into a Low State data structure.
Since we can't easily represent complicated data structures with
key-value pairs, any more complicated requirements (e.g. compound
commands) must instead be delivered via JSON or YAML.
For example::
.. code-block:: bash
curl -si localhost:8000 -d client=local -d tgt='*' \\
-d fun='test.kwarg' -d arg='one=1' -d arg='two=2'
:param entity: raw POST data
'''
# First call out to CherryPy's default processor
cherrypy._cpreqbody.process_urlencoded(entity)
cherrypy._cpreqbody.process_urlencoded(entity)
cherrypy.serving.request.unserialized_data = entity.params
cherrypy.serving.request.raw_body = '' | [
"def",
"urlencoded_processor",
"(",
"entity",
")",
":",
"# First call out to CherryPy's default processor",
"cherrypy",
".",
"_cpreqbody",
".",
"process_urlencoded",
"(",
"entity",
")",
"cherrypy",
".",
"_cpreqbody",
".",
"process_urlencoded",
"(",
"entity",
")",
"cherr... | Accept x-www-form-urlencoded data (run through CherryPy's formatter)
and reformat it into a Low State data structure.
Since we can't easily represent complicated data structures with
key-value pairs, any more complicated requirements (e.g. compound
commands) must instead be delivered via JSON or YAML.
For example::
.. code-block:: bash
curl -si localhost:8000 -d client=local -d tgt='*' \\
-d fun='test.kwarg' -d arg='one=1' -d arg='two=2'
:param entity: raw POST data | [
"Accept",
"x",
"-",
"www",
"-",
"form",
"-",
"urlencoded",
"data",
"(",
"run",
"through",
"CherryPy",
"s",
"formatter",
")",
"and",
"reformat",
"it",
"into",
"a",
"Low",
"State",
"data",
"structure",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L947-L969 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | json_processor | def json_processor(entity):
'''
Unserialize raw POST data in JSON format to a Python data structure.
:param entity: raw POST data
'''
if six.PY2:
body = entity.fp.read()
else:
# https://github.com/cherrypy/cherrypy/pull/1572
contents = BytesIO()
body = entity.fp.read(fp_out=contents)
contents.seek(0)
body = salt.utils.stringutils.to_unicode(contents.read())
del contents
try:
cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body)
except ValueError:
raise cherrypy.HTTPError(400, 'Invalid JSON document')
cherrypy.serving.request.raw_body = body | python | def json_processor(entity):
'''
Unserialize raw POST data in JSON format to a Python data structure.
:param entity: raw POST data
'''
if six.PY2:
body = entity.fp.read()
else:
# https://github.com/cherrypy/cherrypy/pull/1572
contents = BytesIO()
body = entity.fp.read(fp_out=contents)
contents.seek(0)
body = salt.utils.stringutils.to_unicode(contents.read())
del contents
try:
cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body)
except ValueError:
raise cherrypy.HTTPError(400, 'Invalid JSON document')
cherrypy.serving.request.raw_body = body | [
"def",
"json_processor",
"(",
"entity",
")",
":",
"if",
"six",
".",
"PY2",
":",
"body",
"=",
"entity",
".",
"fp",
".",
"read",
"(",
")",
"else",
":",
"# https://github.com/cherrypy/cherrypy/pull/1572",
"contents",
"=",
"BytesIO",
"(",
")",
"body",
"=",
"en... | Unserialize raw POST data in JSON format to a Python data structure.
:param entity: raw POST data | [
"Unserialize",
"raw",
"POST",
"data",
"in",
"JSON",
"format",
"to",
"a",
"Python",
"data",
"structure",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L973-L993 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | yaml_processor | def yaml_processor(entity):
'''
Unserialize raw POST data in YAML format to a Python data structure.
:param entity: raw POST data
'''
if six.PY2:
body = entity.fp.read()
else:
# https://github.com/cherrypy/cherrypy/pull/1572
contents = BytesIO()
body = entity.fp.read(fp_out=contents)
contents.seek(0)
body = salt.utils.stringutils.to_unicode(contents.read())
try:
cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body)
except ValueError:
raise cherrypy.HTTPError(400, 'Invalid YAML document')
cherrypy.serving.request.raw_body = body | python | def yaml_processor(entity):
'''
Unserialize raw POST data in YAML format to a Python data structure.
:param entity: raw POST data
'''
if six.PY2:
body = entity.fp.read()
else:
# https://github.com/cherrypy/cherrypy/pull/1572
contents = BytesIO()
body = entity.fp.read(fp_out=contents)
contents.seek(0)
body = salt.utils.stringutils.to_unicode(contents.read())
try:
cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body)
except ValueError:
raise cherrypy.HTTPError(400, 'Invalid YAML document')
cherrypy.serving.request.raw_body = body | [
"def",
"yaml_processor",
"(",
"entity",
")",
":",
"if",
"six",
".",
"PY2",
":",
"body",
"=",
"entity",
".",
"fp",
".",
"read",
"(",
")",
"else",
":",
"# https://github.com/cherrypy/cherrypy/pull/1572",
"contents",
"=",
"BytesIO",
"(",
")",
"body",
"=",
"en... | Unserialize raw POST data in YAML format to a Python data structure.
:param entity: raw POST data | [
"Unserialize",
"raw",
"POST",
"data",
"in",
"YAML",
"format",
"to",
"a",
"Python",
"data",
"structure",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L997-L1016 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | hypermedia_in | def hypermedia_in():
'''
Unserialize POST/PUT data of a specified Content-Type.
The following custom processors all are intended to format Low State data
and will place that data structure into the request object.
:raises HTTPError: if the request contains a Content-Type that we do not
have a processor for
'''
# Be liberal in what you accept
ct_in_map = {
'application/x-www-form-urlencoded': urlencoded_processor,
'application/json': json_processor,
'application/x-yaml': yaml_processor,
'text/yaml': yaml_processor,
'text/plain': text_processor,
}
# Do not process the body for POST requests that have specified no content
# or have not specified Content-Length
if (cherrypy.request.method.upper() == 'POST'
and cherrypy.request.headers.get('Content-Length', '0') == '0'):
cherrypy.request.process_request_body = False
cherrypy.request.unserialized_data = None
cherrypy.request.body.processors.clear()
cherrypy.request.body.default_proc = cherrypy.HTTPError(
406, 'Content type not supported')
cherrypy.request.body.processors = ct_in_map | python | def hypermedia_in():
'''
Unserialize POST/PUT data of a specified Content-Type.
The following custom processors all are intended to format Low State data
and will place that data structure into the request object.
:raises HTTPError: if the request contains a Content-Type that we do not
have a processor for
'''
# Be liberal in what you accept
ct_in_map = {
'application/x-www-form-urlencoded': urlencoded_processor,
'application/json': json_processor,
'application/x-yaml': yaml_processor,
'text/yaml': yaml_processor,
'text/plain': text_processor,
}
# Do not process the body for POST requests that have specified no content
# or have not specified Content-Length
if (cherrypy.request.method.upper() == 'POST'
and cherrypy.request.headers.get('Content-Length', '0') == '0'):
cherrypy.request.process_request_body = False
cherrypy.request.unserialized_data = None
cherrypy.request.body.processors.clear()
cherrypy.request.body.default_proc = cherrypy.HTTPError(
406, 'Content type not supported')
cherrypy.request.body.processors = ct_in_map | [
"def",
"hypermedia_in",
"(",
")",
":",
"# Be liberal in what you accept",
"ct_in_map",
"=",
"{",
"'application/x-www-form-urlencoded'",
":",
"urlencoded_processor",
",",
"'application/json'",
":",
"json_processor",
",",
"'application/x-yaml'",
":",
"yaml_processor",
",",
"'... | Unserialize POST/PUT data of a specified Content-Type.
The following custom processors all are intended to format Low State data
and will place that data structure into the request object.
:raises HTTPError: if the request contains a Content-Type that we do not
have a processor for | [
"Unserialize",
"POST",
"/",
"PUT",
"data",
"of",
"a",
"specified",
"Content",
"-",
"Type",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1045-L1074 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | lowdata_fmt | def lowdata_fmt():
'''
Validate and format lowdata from incoming unserialized request data
This tool requires that the hypermedia_in tool has already been run.
'''
if cherrypy.request.method.upper() != 'POST':
return
data = cherrypy.request.unserialized_data
# if the data was sent as urlencoded, we need to make it a list.
# this is a very forgiving implementation as different clients set different
# headers for form encoded data (including charset or something similar)
if data and isinstance(data, collections.Mapping):
# Make the 'arg' param a list if not already
if 'arg' in data and not isinstance(data['arg'], list):
data['arg'] = [data['arg']]
# Finally, make a Low State and put it in request
cherrypy.request.lowstate = [data]
else:
cherrypy.serving.request.lowstate = data | python | def lowdata_fmt():
'''
Validate and format lowdata from incoming unserialized request data
This tool requires that the hypermedia_in tool has already been run.
'''
if cherrypy.request.method.upper() != 'POST':
return
data = cherrypy.request.unserialized_data
# if the data was sent as urlencoded, we need to make it a list.
# this is a very forgiving implementation as different clients set different
# headers for form encoded data (including charset or something similar)
if data and isinstance(data, collections.Mapping):
# Make the 'arg' param a list if not already
if 'arg' in data and not isinstance(data['arg'], list):
data['arg'] = [data['arg']]
# Finally, make a Low State and put it in request
cherrypy.request.lowstate = [data]
else:
cherrypy.serving.request.lowstate = data | [
"def",
"lowdata_fmt",
"(",
")",
":",
"if",
"cherrypy",
".",
"request",
".",
"method",
".",
"upper",
"(",
")",
"!=",
"'POST'",
":",
"return",
"data",
"=",
"cherrypy",
".",
"request",
".",
"unserialized_data",
"# if the data was sent as urlencoded, we need to make i... | Validate and format lowdata from incoming unserialized request data
This tool requires that the hypermedia_in tool has already been run. | [
"Validate",
"and",
"format",
"lowdata",
"from",
"incoming",
"unserialized",
"request",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1077-L1100 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | get_app | def get_app(opts):
'''
Returns a WSGI app and a configuration dictionary
'''
apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts
# Add Salt and salt-api config options to the main CherryPy config dict
cherrypy.config['saltopts'] = opts
cherrypy.config['apiopts'] = apiopts
root = API() # cherrypy app
cpyopts = root.get_conf() # cherrypy app opts
return root, apiopts, cpyopts | python | def get_app(opts):
'''
Returns a WSGI app and a configuration dictionary
'''
apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts
# Add Salt and salt-api config options to the main CherryPy config dict
cherrypy.config['saltopts'] = opts
cherrypy.config['apiopts'] = apiopts
root = API() # cherrypy app
cpyopts = root.get_conf() # cherrypy app opts
return root, apiopts, cpyopts | [
"def",
"get_app",
"(",
"opts",
")",
":",
"apiopts",
"=",
"opts",
".",
"get",
"(",
"__name__",
".",
"rsplit",
"(",
"'.'",
",",
"2",
")",
"[",
"-",
"2",
"]",
",",
"{",
"}",
")",
"# rest_cherrypy opts",
"# Add Salt and salt-api config options to the main Cherry... | Returns a WSGI app and a configuration dictionary | [
"Returns",
"a",
"WSGI",
"app",
"and",
"a",
"configuration",
"dictionary"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2927-L2940 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | LowDataAdapter.exec_lowstate | def exec_lowstate(self, client=None, token=None):
'''
Pull a Low State data structure from request and execute the low-data
chunks through Salt. The low-data chunks will be updated to include the
authorization token for the current session.
'''
lowstate = cherrypy.request.lowstate
# Release the session lock before executing any potentially
# long-running Salt commands. This allows different threads to execute
# Salt commands concurrently without blocking.
if cherrypy.request.config.get('tools.sessions.on', False):
cherrypy.session.release_lock()
# if the lowstate loaded isn't a list, lets notify the client
if not isinstance(lowstate, list):
raise cherrypy.HTTPError(400, 'Lowstates must be a list')
# Make any requested additions or modifications to each lowstate, then
# execute each one and yield the result.
for chunk in lowstate:
if token:
chunk['token'] = token
if 'token' in chunk:
# Make sure that auth token is hex
try:
int(chunk['token'], 16)
except (TypeError, ValueError):
raise cherrypy.HTTPError(401, 'Invalid token')
if 'token' in chunk:
# Make sure that auth token is hex
try:
int(chunk['token'], 16)
except (TypeError, ValueError):
raise cherrypy.HTTPError(401, 'Invalid token')
if client:
chunk['client'] = client
# Make any 'arg' params a list if not already.
# This is largely to fix a deficiency in the urlencoded format.
if 'arg' in chunk and not isinstance(chunk['arg'], list):
chunk['arg'] = [chunk['arg']]
ret = self.api.run(chunk)
# Sometimes Salt gives us a return and sometimes an iterator
if isinstance(ret, collections.Iterator):
for i in ret:
yield i
else:
yield ret | python | def exec_lowstate(self, client=None, token=None):
'''
Pull a Low State data structure from request and execute the low-data
chunks through Salt. The low-data chunks will be updated to include the
authorization token for the current session.
'''
lowstate = cherrypy.request.lowstate
# Release the session lock before executing any potentially
# long-running Salt commands. This allows different threads to execute
# Salt commands concurrently without blocking.
if cherrypy.request.config.get('tools.sessions.on', False):
cherrypy.session.release_lock()
# if the lowstate loaded isn't a list, lets notify the client
if not isinstance(lowstate, list):
raise cherrypy.HTTPError(400, 'Lowstates must be a list')
# Make any requested additions or modifications to each lowstate, then
# execute each one and yield the result.
for chunk in lowstate:
if token:
chunk['token'] = token
if 'token' in chunk:
# Make sure that auth token is hex
try:
int(chunk['token'], 16)
except (TypeError, ValueError):
raise cherrypy.HTTPError(401, 'Invalid token')
if 'token' in chunk:
# Make sure that auth token is hex
try:
int(chunk['token'], 16)
except (TypeError, ValueError):
raise cherrypy.HTTPError(401, 'Invalid token')
if client:
chunk['client'] = client
# Make any 'arg' params a list if not already.
# This is largely to fix a deficiency in the urlencoded format.
if 'arg' in chunk and not isinstance(chunk['arg'], list):
chunk['arg'] = [chunk['arg']]
ret = self.api.run(chunk)
# Sometimes Salt gives us a return and sometimes an iterator
if isinstance(ret, collections.Iterator):
for i in ret:
yield i
else:
yield ret | [
"def",
"exec_lowstate",
"(",
"self",
",",
"client",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"lowstate",
"=",
"cherrypy",
".",
"request",
".",
"lowstate",
"# Release the session lock before executing any potentially",
"# long-running Salt commands. This allows di... | Pull a Low State data structure from request and execute the low-data
chunks through Salt. The low-data chunks will be updated to include the
authorization token for the current session. | [
"Pull",
"a",
"Low",
"State",
"data",
"structure",
"from",
"request",
"and",
"execute",
"the",
"low",
"-",
"data",
"chunks",
"through",
"Salt",
".",
"The",
"low",
"-",
"data",
"chunks",
"will",
"be",
"updated",
"to",
"include",
"the",
"authorization",
"toke... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1155-L1208 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | LowDataAdapter.POST | def POST(self, **kwargs):
'''
Send one or more Salt commands in the request body
.. http:post:: /
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
:status 200: |200|
:status 400: |400|
:status 401: |401|
:status 406: |406|
:term:`lowstate` data describing Salt commands must be sent in the
request body.
**Example request:**
.. code-block:: bash
curl -sSik https://localhost:8000 \\
-b ~/cookies.txt \\
-H "Accept: application/x-yaml" \\
-H "Content-type: application/json" \\
-d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]'
.. code-block:: text
POST / HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
X-Auth-Token: d40d1e1e
Content-Type: application/json
[{"client": "local", "tgt": "*", "fun": "test.ping"}]
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 200
Allow: GET, HEAD, POST
Content-Type: application/x-yaml
return:
- ms-0: true
ms-1: true
ms-2: true
ms-3: true
ms-4: true
'''
return {
'return': list(self.exec_lowstate(
token=cherrypy.session.get('token')))
} | python | def POST(self, **kwargs):
'''
Send one or more Salt commands in the request body
.. http:post:: /
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
:status 200: |200|
:status 400: |400|
:status 401: |401|
:status 406: |406|
:term:`lowstate` data describing Salt commands must be sent in the
request body.
**Example request:**
.. code-block:: bash
curl -sSik https://localhost:8000 \\
-b ~/cookies.txt \\
-H "Accept: application/x-yaml" \\
-H "Content-type: application/json" \\
-d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]'
.. code-block:: text
POST / HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
X-Auth-Token: d40d1e1e
Content-Type: application/json
[{"client": "local", "tgt": "*", "fun": "test.ping"}]
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 200
Allow: GET, HEAD, POST
Content-Type: application/x-yaml
return:
- ms-0: true
ms-1: true
ms-2: true
ms-3: true
ms-4: true
'''
return {
'return': list(self.exec_lowstate(
token=cherrypy.session.get('token')))
} | [
"def",
"POST",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"{",
"'return'",
":",
"list",
"(",
"self",
".",
"exec_lowstate",
"(",
"token",
"=",
"cherrypy",
".",
"session",
".",
"get",
"(",
"'token'",
")",
")",
")",
"}"
] | Send one or more Salt commands in the request body
.. http:post:: /
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
:status 200: |200|
:status 400: |400|
:status 401: |401|
:status 406: |406|
:term:`lowstate` data describing Salt commands must be sent in the
request body.
**Example request:**
.. code-block:: bash
curl -sSik https://localhost:8000 \\
-b ~/cookies.txt \\
-H "Accept: application/x-yaml" \\
-H "Content-type: application/json" \\
-d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]'
.. code-block:: text
POST / HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
X-Auth-Token: d40d1e1e
Content-Type: application/json
[{"client": "local", "tgt": "*", "fun": "test.ping"}]
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 200
Allow: GET, HEAD, POST
Content-Type: application/x-yaml
return:
- ms-0: true
ms-1: true
ms-2: true
ms-3: true
ms-4: true | [
"Send",
"one",
"or",
"more",
"Salt",
"commands",
"in",
"the",
"request",
"body"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1251-L1310 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Minions.GET | def GET(self, mid=None):
'''
A convenience URL for getting lists of minions or getting minion
details
.. http:get:: /minions/(mid)
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/minions/ms-3
.. code-block:: text
GET /minions/ms-3 HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 129005
Content-Type: application/x-yaml
return:
- ms-3:
grains.items:
...
'''
cherrypy.request.lowstate = [{
'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items',
}]
return {
'return': list(self.exec_lowstate(
token=cherrypy.session.get('token'))),
} | python | def GET(self, mid=None):
'''
A convenience URL for getting lists of minions or getting minion
details
.. http:get:: /minions/(mid)
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/minions/ms-3
.. code-block:: text
GET /minions/ms-3 HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 129005
Content-Type: application/x-yaml
return:
- ms-3:
grains.items:
...
'''
cherrypy.request.lowstate = [{
'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items',
}]
return {
'return': list(self.exec_lowstate(
token=cherrypy.session.get('token'))),
} | [
"def",
"GET",
"(",
"self",
",",
"mid",
"=",
"None",
")",
":",
"cherrypy",
".",
"request",
".",
"lowstate",
"=",
"[",
"{",
"'client'",
":",
"'local'",
",",
"'tgt'",
":",
"mid",
"or",
"'*'",
",",
"'fun'",
":",
"'grains.items'",
",",
"}",
"]",
"return... | A convenience URL for getting lists of minions or getting minion
details
.. http:get:: /minions/(mid)
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/minions/ms-3
.. code-block:: text
GET /minions/ms-3 HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 129005
Content-Type: application/x-yaml
return:
- ms-3:
grains.items:
... | [
"A",
"convenience",
"URL",
"for",
"getting",
"lists",
"of",
"minions",
"or",
"getting",
"minion",
"details"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1321-L1366 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Minions.POST | def POST(self, **kwargs):
'''
Start an execution command and immediately return the job id
.. http:post:: /minions
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
:status 200: |200|
:status 400: |400|
:status 401: |401|
:status 406: |406|
Lowstate data describing Salt commands must be sent in the request
body. The ``client`` option will be set to
:py:meth:`~salt.client.LocalClient.local_async`.
**Example request:**
.. code-block:: bash
curl -sSi localhost:8000/minions \\
-b ~/cookies.txt \\
-H "Accept: application/x-yaml" \\
-d '[{"tgt": "*", "fun": "status.diskusage"}]'
.. code-block:: text
POST /minions HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
Content-Type: application/json
tgt=*&fun=status.diskusage
**Example response:**
.. code-block:: text
HTTP/1.1 202 Accepted
Content-Length: 86
Content-Type: application/x-yaml
return:
- jid: '20130603122505459265'
minions: [ms-4, ms-3, ms-2, ms-1, ms-0]
_links:
jobs:
- href: /jobs/20130603122505459265
'''
job_data = list(self.exec_lowstate(client='local_async',
token=cherrypy.session.get('token')))
cherrypy.response.status = 202
return {
'return': job_data,
'_links': {
'jobs': [{'href': '/jobs/{0}'.format(i['jid'])}
for i in job_data if i],
},
} | python | def POST(self, **kwargs):
'''
Start an execution command and immediately return the job id
.. http:post:: /minions
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
:status 200: |200|
:status 400: |400|
:status 401: |401|
:status 406: |406|
Lowstate data describing Salt commands must be sent in the request
body. The ``client`` option will be set to
:py:meth:`~salt.client.LocalClient.local_async`.
**Example request:**
.. code-block:: bash
curl -sSi localhost:8000/minions \\
-b ~/cookies.txt \\
-H "Accept: application/x-yaml" \\
-d '[{"tgt": "*", "fun": "status.diskusage"}]'
.. code-block:: text
POST /minions HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
Content-Type: application/json
tgt=*&fun=status.diskusage
**Example response:**
.. code-block:: text
HTTP/1.1 202 Accepted
Content-Length: 86
Content-Type: application/x-yaml
return:
- jid: '20130603122505459265'
minions: [ms-4, ms-3, ms-2, ms-1, ms-0]
_links:
jobs:
- href: /jobs/20130603122505459265
'''
job_data = list(self.exec_lowstate(client='local_async',
token=cherrypy.session.get('token')))
cherrypy.response.status = 202
return {
'return': job_data,
'_links': {
'jobs': [{'href': '/jobs/{0}'.format(i['jid'])}
for i in job_data if i],
},
} | [
"def",
"POST",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"job_data",
"=",
"list",
"(",
"self",
".",
"exec_lowstate",
"(",
"client",
"=",
"'local_async'",
",",
"token",
"=",
"cherrypy",
".",
"session",
".",
"get",
"(",
"'token'",
")",
")",
")",
... | Start an execution command and immediately return the job id
.. http:post:: /minions
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
:status 200: |200|
:status 400: |400|
:status 401: |401|
:status 406: |406|
Lowstate data describing Salt commands must be sent in the request
body. The ``client`` option will be set to
:py:meth:`~salt.client.LocalClient.local_async`.
**Example request:**
.. code-block:: bash
curl -sSi localhost:8000/minions \\
-b ~/cookies.txt \\
-H "Accept: application/x-yaml" \\
-d '[{"tgt": "*", "fun": "status.diskusage"}]'
.. code-block:: text
POST /minions HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
Content-Type: application/json
tgt=*&fun=status.diskusage
**Example response:**
.. code-block:: text
HTTP/1.1 202 Accepted
Content-Length: 86
Content-Type: application/x-yaml
return:
- jid: '20130603122505459265'
minions: [ms-4, ms-3, ms-2, ms-1, ms-0]
_links:
jobs:
- href: /jobs/20130603122505459265 | [
"Start",
"an",
"execution",
"command",
"and",
"immediately",
"return",
"the",
"job",
"id"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1368-L1432 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Jobs.GET | def GET(self, jid=None, timeout=''):
'''
A convenience URL for getting lists of previously run jobs or getting
the return from a single job
.. http:get:: /jobs/(jid)
List jobs or show a single job from the job cache.
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/jobs
.. code-block:: text
GET /jobs HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 165
Content-Type: application/x-yaml
return:
- '20121130104633606931':
Arguments:
- '3'
Function: test.fib
Start Time: 2012, Nov 30 10:46:33.606931
Target: jerry
Target-type: glob
**Example request:**
.. code-block:: bash
curl -i localhost:8000/jobs/20121130104633606931
.. code-block:: text
GET /jobs/20121130104633606931 HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 73
Content-Type: application/x-yaml
info:
- Arguments:
- '3'
Function: test.fib
Minions:
- jerry
Start Time: 2012, Nov 30 10:46:33.606931
Target: '*'
Target-type: glob
User: saltdev
jid: '20121130104633606931'
return:
- jerry:
- - 0
- 1
- 1
- 2
- 6.9141387939453125e-06
'''
lowstate = {'client': 'runner'}
if jid:
lowstate.update({'fun': 'jobs.list_job', 'jid': jid})
else:
lowstate.update({'fun': 'jobs.list_jobs'})
cherrypy.request.lowstate = [lowstate]
job_ret_info = list(self.exec_lowstate(
token=cherrypy.session.get('token')))
ret = {}
if jid:
ret['info'] = [job_ret_info[0]]
minion_ret = {}
returns = job_ret_info[0].get('Result')
for minion in returns:
if u'return' in returns[minion]:
minion_ret[minion] = returns[minion].get(u'return')
else:
minion_ret[minion] = returns[minion].get('return')
ret['return'] = [minion_ret]
else:
ret['return'] = [job_ret_info[0]]
return ret | python | def GET(self, jid=None, timeout=''):
'''
A convenience URL for getting lists of previously run jobs or getting
the return from a single job
.. http:get:: /jobs/(jid)
List jobs or show a single job from the job cache.
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/jobs
.. code-block:: text
GET /jobs HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 165
Content-Type: application/x-yaml
return:
- '20121130104633606931':
Arguments:
- '3'
Function: test.fib
Start Time: 2012, Nov 30 10:46:33.606931
Target: jerry
Target-type: glob
**Example request:**
.. code-block:: bash
curl -i localhost:8000/jobs/20121130104633606931
.. code-block:: text
GET /jobs/20121130104633606931 HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 73
Content-Type: application/x-yaml
info:
- Arguments:
- '3'
Function: test.fib
Minions:
- jerry
Start Time: 2012, Nov 30 10:46:33.606931
Target: '*'
Target-type: glob
User: saltdev
jid: '20121130104633606931'
return:
- jerry:
- - 0
- 1
- 1
- 2
- 6.9141387939453125e-06
'''
lowstate = {'client': 'runner'}
if jid:
lowstate.update({'fun': 'jobs.list_job', 'jid': jid})
else:
lowstate.update({'fun': 'jobs.list_jobs'})
cherrypy.request.lowstate = [lowstate]
job_ret_info = list(self.exec_lowstate(
token=cherrypy.session.get('token')))
ret = {}
if jid:
ret['info'] = [job_ret_info[0]]
minion_ret = {}
returns = job_ret_info[0].get('Result')
for minion in returns:
if u'return' in returns[minion]:
minion_ret[minion] = returns[minion].get(u'return')
else:
minion_ret[minion] = returns[minion].get('return')
ret['return'] = [minion_ret]
else:
ret['return'] = [job_ret_info[0]]
return ret | [
"def",
"GET",
"(",
"self",
",",
"jid",
"=",
"None",
",",
"timeout",
"=",
"''",
")",
":",
"lowstate",
"=",
"{",
"'client'",
":",
"'runner'",
"}",
"if",
"jid",
":",
"lowstate",
".",
"update",
"(",
"{",
"'fun'",
":",
"'jobs.list_job'",
",",
"'jid'",
"... | A convenience URL for getting lists of previously run jobs or getting
the return from a single job
.. http:get:: /jobs/(jid)
List jobs or show a single job from the job cache.
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/jobs
.. code-block:: text
GET /jobs HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 165
Content-Type: application/x-yaml
return:
- '20121130104633606931':
Arguments:
- '3'
Function: test.fib
Start Time: 2012, Nov 30 10:46:33.606931
Target: jerry
Target-type: glob
**Example request:**
.. code-block:: bash
curl -i localhost:8000/jobs/20121130104633606931
.. code-block:: text
GET /jobs/20121130104633606931 HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 73
Content-Type: application/x-yaml
info:
- Arguments:
- '3'
Function: test.fib
Minions:
- jerry
Start Time: 2012, Nov 30 10:46:33.606931
Target: '*'
Target-type: glob
User: saltdev
jid: '20121130104633606931'
return:
- jerry:
- - 0
- 1
- 1
- 2
- 6.9141387939453125e-06 | [
"A",
"convenience",
"URL",
"for",
"getting",
"lists",
"of",
"previously",
"run",
"jobs",
"or",
"getting",
"the",
"return",
"from",
"a",
"single",
"job"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1440-L1548 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Keys.GET | def GET(self, mid=None):
'''
Show the list of minion keys or detail on a specific key
.. versionadded:: 2014.7.0
.. http:get:: /keys/(mid)
List all keys or show a specific key
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/keys
.. code-block:: text
GET /keys HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 165
Content-Type: application/x-yaml
return:
local:
- master.pem
- master.pub
minions:
- jerry
minions_pre: []
minions_rejected: []
**Example request:**
.. code-block:: bash
curl -i localhost:8000/keys/jerry
.. code-block:: text
GET /keys/jerry HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 73
Content-Type: application/x-yaml
return:
minions:
jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b
'''
if mid:
lowstate = [{
'client': 'wheel',
'fun': 'key.finger',
'match': mid,
}]
else:
lowstate = [{
'client': 'wheel',
'fun': 'key.list_all',
}]
cherrypy.request.lowstate = lowstate
result = self.exec_lowstate(token=cherrypy.session.get('token'))
return {'return': next(result, {}).get('data', {}).get('return', {})} | python | def GET(self, mid=None):
'''
Show the list of minion keys or detail on a specific key
.. versionadded:: 2014.7.0
.. http:get:: /keys/(mid)
List all keys or show a specific key
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/keys
.. code-block:: text
GET /keys HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 165
Content-Type: application/x-yaml
return:
local:
- master.pem
- master.pub
minions:
- jerry
minions_pre: []
minions_rejected: []
**Example request:**
.. code-block:: bash
curl -i localhost:8000/keys/jerry
.. code-block:: text
GET /keys/jerry HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 73
Content-Type: application/x-yaml
return:
minions:
jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b
'''
if mid:
lowstate = [{
'client': 'wheel',
'fun': 'key.finger',
'match': mid,
}]
else:
lowstate = [{
'client': 'wheel',
'fun': 'key.list_all',
}]
cherrypy.request.lowstate = lowstate
result = self.exec_lowstate(token=cherrypy.session.get('token'))
return {'return': next(result, {}).get('data', {}).get('return', {})} | [
"def",
"GET",
"(",
"self",
",",
"mid",
"=",
"None",
")",
":",
"if",
"mid",
":",
"lowstate",
"=",
"[",
"{",
"'client'",
":",
"'wheel'",
",",
"'fun'",
":",
"'key.finger'",
",",
"'match'",
":",
"mid",
",",
"}",
"]",
"else",
":",
"lowstate",
"=",
"["... | Show the list of minion keys or detail on a specific key
.. versionadded:: 2014.7.0
.. http:get:: /keys/(mid)
List all keys or show a specific key
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000/keys
.. code-block:: text
GET /keys HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 165
Content-Type: application/x-yaml
return:
local:
- master.pem
- master.pub
minions:
- jerry
minions_pre: []
minions_rejected: []
**Example request:**
.. code-block:: bash
curl -i localhost:8000/keys/jerry
.. code-block:: text
GET /keys/jerry HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 73
Content-Type: application/x-yaml
return:
minions:
jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b | [
"Show",
"the",
"list",
"of",
"minion",
"keys",
"or",
"detail",
"on",
"a",
"specific",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1561-L1646 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Keys.POST | def POST(self, **kwargs):
r'''
Easily generate keys for a minion and auto-accept the new key
Accepts all the same parameters as the :py:func:`key.gen_accept
<salt.wheel.key.gen_accept>`.
.. note:: A note about ``curl``
Avoid using the ``-i`` flag or HTTP headers will be written and
produce an invalid tar file.
Example partial kickstart script to bootstrap a new minion:
.. code-block:: text
%post
mkdir -p /etc/salt/pki/minion
curl -sSk https://localhost:8000/keys \
-d mid=jerry \
-d username=kickstart \
-d password=kickstart \
-d eauth=pam \
| tar -C /etc/salt/pki/minion -xf -
mkdir -p /etc/salt/minion.d
printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf
%end
.. http:post:: /keys
Generate a public and private key and return both as a tarball
Authentication credentials must be passed in the request.
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -sSk https://localhost:8000/keys \
-d mid=jerry \
-d username=kickstart \
-d password=kickstart \
-d eauth=pam \
-o jerry-salt-keys.tar
.. code-block:: text
POST /keys HTTP/1.1
Host: localhost:8000
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 10240
Content-Disposition: attachment; filename="saltkeys-jerry.tar"
Content-Type: application/x-tar
jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000
'''
lowstate = cherrypy.request.lowstate
lowstate[0].update({
'client': 'wheel',
'fun': 'key.gen_accept',
})
if 'mid' in lowstate[0]:
lowstate[0]['id_'] = lowstate[0].pop('mid')
result = self.exec_lowstate()
ret = next(result, {}).get('data', {}).get('return', {})
pub_key = ret.get('pub', '')
pub_key_file = tarfile.TarInfo('minion.pub')
pub_key_file.size = len(pub_key)
priv_key = ret.get('priv', '')
priv_key_file = tarfile.TarInfo('minion.pem')
priv_key_file.size = len(priv_key)
fileobj = BytesIO()
tarball = tarfile.open(fileobj=fileobj, mode='w')
if six.PY3:
pub_key = pub_key.encode(__salt_system_encoding__)
priv_key = priv_key.encode(__salt_system_encoding__)
tarball.addfile(pub_key_file, BytesIO(pub_key))
tarball.addfile(priv_key_file, BytesIO(priv_key))
tarball.close()
headers = cherrypy.response.headers
headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_'])
headers['Content-Type'] = 'application/x-tar'
headers['Content-Length'] = len(fileobj.getvalue())
headers['Cache-Control'] = 'no-cache'
fileobj.seek(0)
return fileobj | python | def POST(self, **kwargs):
r'''
Easily generate keys for a minion and auto-accept the new key
Accepts all the same parameters as the :py:func:`key.gen_accept
<salt.wheel.key.gen_accept>`.
.. note:: A note about ``curl``
Avoid using the ``-i`` flag or HTTP headers will be written and
produce an invalid tar file.
Example partial kickstart script to bootstrap a new minion:
.. code-block:: text
%post
mkdir -p /etc/salt/pki/minion
curl -sSk https://localhost:8000/keys \
-d mid=jerry \
-d username=kickstart \
-d password=kickstart \
-d eauth=pam \
| tar -C /etc/salt/pki/minion -xf -
mkdir -p /etc/salt/minion.d
printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf
%end
.. http:post:: /keys
Generate a public and private key and return both as a tarball
Authentication credentials must be passed in the request.
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -sSk https://localhost:8000/keys \
-d mid=jerry \
-d username=kickstart \
-d password=kickstart \
-d eauth=pam \
-o jerry-salt-keys.tar
.. code-block:: text
POST /keys HTTP/1.1
Host: localhost:8000
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 10240
Content-Disposition: attachment; filename="saltkeys-jerry.tar"
Content-Type: application/x-tar
jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000
'''
lowstate = cherrypy.request.lowstate
lowstate[0].update({
'client': 'wheel',
'fun': 'key.gen_accept',
})
if 'mid' in lowstate[0]:
lowstate[0]['id_'] = lowstate[0].pop('mid')
result = self.exec_lowstate()
ret = next(result, {}).get('data', {}).get('return', {})
pub_key = ret.get('pub', '')
pub_key_file = tarfile.TarInfo('minion.pub')
pub_key_file.size = len(pub_key)
priv_key = ret.get('priv', '')
priv_key_file = tarfile.TarInfo('minion.pem')
priv_key_file.size = len(priv_key)
fileobj = BytesIO()
tarball = tarfile.open(fileobj=fileobj, mode='w')
if six.PY3:
pub_key = pub_key.encode(__salt_system_encoding__)
priv_key = priv_key.encode(__salt_system_encoding__)
tarball.addfile(pub_key_file, BytesIO(pub_key))
tarball.addfile(priv_key_file, BytesIO(priv_key))
tarball.close()
headers = cherrypy.response.headers
headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_'])
headers['Content-Type'] = 'application/x-tar'
headers['Content-Length'] = len(fileobj.getvalue())
headers['Cache-Control'] = 'no-cache'
fileobj.seek(0)
return fileobj | [
"def",
"POST",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"lowstate",
"=",
"cherrypy",
".",
"request",
".",
"lowstate",
"lowstate",
"[",
"0",
"]",
".",
"update",
"(",
"{",
"'client'",
":",
"'wheel'",
",",
"'fun'",
":",
"'key.gen_accept'",
",",
"... | r'''
Easily generate keys for a minion and auto-accept the new key
Accepts all the same parameters as the :py:func:`key.gen_accept
<salt.wheel.key.gen_accept>`.
.. note:: A note about ``curl``
Avoid using the ``-i`` flag or HTTP headers will be written and
produce an invalid tar file.
Example partial kickstart script to bootstrap a new minion:
.. code-block:: text
%post
mkdir -p /etc/salt/pki/minion
curl -sSk https://localhost:8000/keys \
-d mid=jerry \
-d username=kickstart \
-d password=kickstart \
-d eauth=pam \
| tar -C /etc/salt/pki/minion -xf -
mkdir -p /etc/salt/minion.d
printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf
%end
.. http:post:: /keys
Generate a public and private key and return both as a tarball
Authentication credentials must be passed in the request.
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -sSk https://localhost:8000/keys \
-d mid=jerry \
-d username=kickstart \
-d password=kickstart \
-d eauth=pam \
-o jerry-salt-keys.tar
.. code-block:: text
POST /keys HTTP/1.1
Host: localhost:8000
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 10240
Content-Disposition: attachment; filename="saltkeys-jerry.tar"
Content-Type: application/x-tar
jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 | [
"r",
"Easily",
"generate",
"keys",
"for",
"a",
"minion",
"and",
"auto",
"-",
"accept",
"the",
"new",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1649-L1752 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Login.POST | def POST(self, **kwargs):
'''
:ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system
.. http:post:: /login
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:form eauth: the eauth backend configured for the user
:form username: username
:form password: password
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -si localhost:8000/login \\
-c ~/cookies.txt \\
-H "Accept: application/json" \\
-H "Content-type: application/json" \\
-d '{
"username": "saltuser",
"password": "saltuser",
"eauth": "auto"
}'
.. code-block:: text
POST / HTTP/1.1
Host: localhost:8000
Content-Length: 42
Content-Type: application/json
Accept: application/json
{"username": "saltuser", "password": "saltuser", "eauth": "auto"}
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 206
X-Auth-Token: 6d1b722e
Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/
{"return": {
"token": "6d1b722e",
"start": 1363805943.776223,
"expire": 1363849143.776224,
"user": "saltuser",
"eauth": "pam",
"perms": [
"grains.*",
"status.*",
"sys.*",
"test.*"
]
}}
'''
if not self.api._is_master_running():
raise salt.exceptions.SaltDaemonNotRunning(
'Salt Master is not available.')
# the urlencoded_processor will wrap this in a list
if isinstance(cherrypy.serving.request.lowstate, list):
creds = cherrypy.serving.request.lowstate[0]
else:
creds = cherrypy.serving.request.lowstate
username = creds.get('username', None)
# Validate against the whitelist.
if not salt_api_acl_tool(username, cherrypy.request):
raise cherrypy.HTTPError(401)
# Mint token.
token = self.auth.mk_token(creds)
if 'token' not in token:
raise cherrypy.HTTPError(401,
'Could not authenticate using provided credentials')
cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id
cherrypy.session['token'] = token['token']
cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60
# Grab eauth config for the current backend for the current user
try:
eauth = self.opts.get('external_auth', {}).get(token['eauth'], {})
if token['eauth'] == 'django' and '^model' in eauth:
perms = token['auth_list']
else:
# Get sum of '*' perms, user-specific perms, and group-specific perms
perms = eauth.get(token['name'], [])
perms.extend(eauth.get('*', []))
if 'groups' in token and token['groups']:
user_groups = set(token['groups'])
eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')])
for group in user_groups & eauth_groups:
perms.extend(eauth['{0}%'.format(group)])
if not perms:
logger.debug("Eauth permission list not found.")
except Exception:
logger.debug(
"Configuration for external_auth malformed for eauth '%s', "
"and user '%s'.", token.get('eauth'), token.get('name'),
exc_info=True
)
perms = None
return {'return': [{
'token': cherrypy.session.id,
'expire': token['expire'],
'start': token['start'],
'user': token['name'],
'eauth': token['eauth'],
'perms': perms or {},
}]} | python | def POST(self, **kwargs):
'''
:ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system
.. http:post:: /login
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:form eauth: the eauth backend configured for the user
:form username: username
:form password: password
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -si localhost:8000/login \\
-c ~/cookies.txt \\
-H "Accept: application/json" \\
-H "Content-type: application/json" \\
-d '{
"username": "saltuser",
"password": "saltuser",
"eauth": "auto"
}'
.. code-block:: text
POST / HTTP/1.1
Host: localhost:8000
Content-Length: 42
Content-Type: application/json
Accept: application/json
{"username": "saltuser", "password": "saltuser", "eauth": "auto"}
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 206
X-Auth-Token: 6d1b722e
Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/
{"return": {
"token": "6d1b722e",
"start": 1363805943.776223,
"expire": 1363849143.776224,
"user": "saltuser",
"eauth": "pam",
"perms": [
"grains.*",
"status.*",
"sys.*",
"test.*"
]
}}
'''
if not self.api._is_master_running():
raise salt.exceptions.SaltDaemonNotRunning(
'Salt Master is not available.')
# the urlencoded_processor will wrap this in a list
if isinstance(cherrypy.serving.request.lowstate, list):
creds = cherrypy.serving.request.lowstate[0]
else:
creds = cherrypy.serving.request.lowstate
username = creds.get('username', None)
# Validate against the whitelist.
if not salt_api_acl_tool(username, cherrypy.request):
raise cherrypy.HTTPError(401)
# Mint token.
token = self.auth.mk_token(creds)
if 'token' not in token:
raise cherrypy.HTTPError(401,
'Could not authenticate using provided credentials')
cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id
cherrypy.session['token'] = token['token']
cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60
# Grab eauth config for the current backend for the current user
try:
eauth = self.opts.get('external_auth', {}).get(token['eauth'], {})
if token['eauth'] == 'django' and '^model' in eauth:
perms = token['auth_list']
else:
# Get sum of '*' perms, user-specific perms, and group-specific perms
perms = eauth.get(token['name'], [])
perms.extend(eauth.get('*', []))
if 'groups' in token and token['groups']:
user_groups = set(token['groups'])
eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')])
for group in user_groups & eauth_groups:
perms.extend(eauth['{0}%'.format(group)])
if not perms:
logger.debug("Eauth permission list not found.")
except Exception:
logger.debug(
"Configuration for external_auth malformed for eauth '%s', "
"and user '%s'.", token.get('eauth'), token.get('name'),
exc_info=True
)
perms = None
return {'return': [{
'token': cherrypy.session.id,
'expire': token['expire'],
'start': token['start'],
'user': token['name'],
'eauth': token['eauth'],
'perms': perms or {},
}]} | [
"def",
"POST",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"api",
".",
"_is_master_running",
"(",
")",
":",
"raise",
"salt",
".",
"exceptions",
".",
"SaltDaemonNotRunning",
"(",
"'Salt Master is not available.'",
")",
"# the url... | :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system
.. http:post:: /login
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:form eauth: the eauth backend configured for the user
:form username: username
:form password: password
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -si localhost:8000/login \\
-c ~/cookies.txt \\
-H "Accept: application/json" \\
-H "Content-type: application/json" \\
-d '{
"username": "saltuser",
"password": "saltuser",
"eauth": "auto"
}'
.. code-block:: text
POST / HTTP/1.1
Host: localhost:8000
Content-Length: 42
Content-Type: application/json
Accept: application/json
{"username": "saltuser", "password": "saltuser", "eauth": "auto"}
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 206
X-Auth-Token: 6d1b722e
Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/
{"return": {
"token": "6d1b722e",
"start": 1363805943.776223,
"expire": 1363849143.776224,
"user": "saltuser",
"eauth": "pam",
"perms": [
"grains.*",
"status.*",
"sys.*",
"test.*"
]
}} | [
":",
"ref",
":",
"Authenticate",
"<rest_cherrypy",
"-",
"auth",
">",
"against",
"Salt",
"s",
"eauth",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1805-L1932 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Token.POST | def POST(self, **kwargs):
r'''
.. http:post:: /token
Generate a Salt eauth token
:status 200: |200|
:status 400: |400|
:status 401: |401|
**Example request:**
.. code-block:: bash
curl -sSk https://localhost:8000/token \
-H 'Content-type: application/json' \
-d '{
"username": "saltdev",
"password": "saltdev",
"eauth": "auto"
}'
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Type: application/json
[{
"start": 1494987445.528182,
"token": "e72ca1655d05...",
"expire": 1495030645.528183,
"name": "saltdev",
"eauth": "auto"
}]
'''
for creds in cherrypy.request.lowstate:
try:
creds.update({
'client': 'runner',
'fun': 'auth.mk_token',
'kwarg': {
'username': creds['username'],
'password': creds['password'],
'eauth': creds['eauth'],
},
})
except KeyError:
raise cherrypy.HTTPError(400,
'Require "username", "password", and "eauth" params')
return list(self.exec_lowstate()) | python | def POST(self, **kwargs):
r'''
.. http:post:: /token
Generate a Salt eauth token
:status 200: |200|
:status 400: |400|
:status 401: |401|
**Example request:**
.. code-block:: bash
curl -sSk https://localhost:8000/token \
-H 'Content-type: application/json' \
-d '{
"username": "saltdev",
"password": "saltdev",
"eauth": "auto"
}'
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Type: application/json
[{
"start": 1494987445.528182,
"token": "e72ca1655d05...",
"expire": 1495030645.528183,
"name": "saltdev",
"eauth": "auto"
}]
'''
for creds in cherrypy.request.lowstate:
try:
creds.update({
'client': 'runner',
'fun': 'auth.mk_token',
'kwarg': {
'username': creds['username'],
'password': creds['password'],
'eauth': creds['eauth'],
},
})
except KeyError:
raise cherrypy.HTTPError(400,
'Require "username", "password", and "eauth" params')
return list(self.exec_lowstate()) | [
"def",
"POST",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"creds",
"in",
"cherrypy",
".",
"request",
".",
"lowstate",
":",
"try",
":",
"creds",
".",
"update",
"(",
"{",
"'client'",
":",
"'runner'",
",",
"'fun'",
":",
"'auth.mk_token'",
",... | r'''
.. http:post:: /token
Generate a Salt eauth token
:status 200: |200|
:status 400: |400|
:status 401: |401|
**Example request:**
.. code-block:: bash
curl -sSk https://localhost:8000/token \
-H 'Content-type: application/json' \
-d '{
"username": "saltdev",
"password": "saltdev",
"eauth": "auto"
}'
**Example response:**
.. code-block:: text
HTTP/1.1 200 OK
Content-Type: application/json
[{
"start": 1494987445.528182,
"token": "e72ca1655d05...",
"expire": 1495030645.528183,
"name": "saltdev",
"eauth": "auto"
}] | [
"r",
"..",
"http",
":",
"post",
"::",
"/",
"token"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1964-L2016 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Events._is_valid_token | def _is_valid_token(self, auth_token):
'''
Check if this is a valid salt-api token or valid Salt token
salt-api tokens are regular session tokens that tie back to a real Salt
token. Salt tokens are tokens generated by Salt's eauth system.
:return bool: True if valid, False if not valid.
'''
# Make sure that auth token is hex. If it's None, or something other
# than hex, this will raise a ValueError.
try:
int(auth_token, 16)
except (TypeError, ValueError):
return False
# First check if the given token is in our session table; if so it's a
# salt-api token and we need to get the Salt token from there.
orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None))
# If it's not in the session table, assume it's a regular Salt token.
salt_token = orig_session.get('token', auth_token)
# The eauth system does not currently support perms for the event
# stream, so we're just checking if the token exists not if the token
# allows access.
if salt_token and self.resolver.get_token(salt_token):
return True
return False | python | def _is_valid_token(self, auth_token):
'''
Check if this is a valid salt-api token or valid Salt token
salt-api tokens are regular session tokens that tie back to a real Salt
token. Salt tokens are tokens generated by Salt's eauth system.
:return bool: True if valid, False if not valid.
'''
# Make sure that auth token is hex. If it's None, or something other
# than hex, this will raise a ValueError.
try:
int(auth_token, 16)
except (TypeError, ValueError):
return False
# First check if the given token is in our session table; if so it's a
# salt-api token and we need to get the Salt token from there.
orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None))
# If it's not in the session table, assume it's a regular Salt token.
salt_token = orig_session.get('token', auth_token)
# The eauth system does not currently support perms for the event
# stream, so we're just checking if the token exists not if the token
# allows access.
if salt_token and self.resolver.get_token(salt_token):
return True
return False | [
"def",
"_is_valid_token",
"(",
"self",
",",
"auth_token",
")",
":",
"# Make sure that auth token is hex. If it's None, or something other",
"# than hex, this will raise a ValueError.",
"try",
":",
"int",
"(",
"auth_token",
",",
"16",
")",
"except",
"(",
"TypeError",
",",
... | Check if this is a valid salt-api token or valid Salt token
salt-api tokens are regular session tokens that tie back to a real Salt
token. Salt tokens are tokens generated by Salt's eauth system.
:return bool: True if valid, False if not valid. | [
"Check",
"if",
"this",
"is",
"a",
"valid",
"salt",
"-",
"api",
"token",
"or",
"valid",
"Salt",
"token"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2191-L2219 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Events.GET | def GET(self, token=None, salt_token=None):
r'''
An HTTP stream of the Salt master event bus
This stream is formatted per the Server Sent Events (SSE) spec. Each
event is formatted as JSON.
.. http:get:: /events
:status 200: |200|
:status 401: |401|
:status 406: |406|
:query token: **optional** parameter containing the token
ordinarily supplied via the X-Auth-Token header in order to
allow cross-domain requests in browsers that do not include
CORS support in the EventSource API. E.g.,
``curl -NsS localhost:8000/events?token=308650d``
:query salt_token: **optional** parameter containing a raw Salt
*eauth token* (not to be confused with the token returned from
the /login URL). E.g.,
``curl -NsS localhost:8000/events?salt_token=30742765``
**Example request:**
.. code-block:: bash
curl -NsS localhost:8000/events
.. code-block:: text
GET /events HTTP/1.1
Host: localhost:8000
**Example response:**
Note, the ``tag`` field is not part of the spec. SSE compliant clients
should ignore unknown fields. This addition allows non-compliant
clients to only watch for certain tags without having to deserialze the
JSON object each time.
.. code-block:: text
HTTP/1.1 200 OK
Connection: keep-alive
Cache-Control: no-cache
Content-Type: text/event-stream;charset=utf-8
retry: 400
tag: salt/job/20130802115730568475/new
data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}}
tag: salt/job/20130802115730568475/ret/jerry
data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}}
The event stream can be easily consumed via JavaScript:
.. code-block:: javascript
var source = new EventSource('/events');
source.onopen = function() { console.info('Listening ...') };
source.onerror = function(err) { console.error(err) };
source.onmessage = function(message) {
var saltEvent = JSON.parse(message.data);
console.log(saltEvent.tag, saltEvent.data);
};
Note, the SSE stream is fast and completely asynchronous and Salt is
very fast. If a job is created using a regular POST request, it is
possible that the job return will be available on the SSE stream before
the response for the POST request arrives. It is important to take that
asynchronicity into account when designing an application. Below are
some general guidelines.
* Subscribe to the SSE stream _before_ creating any events.
* Process SSE events directly as they arrive and don't wait for any
other process to "complete" first (like an ajax request).
* Keep a buffer of events if the event stream must be used for
synchronous lookups.
* Be cautious in writing Salt's event stream directly to the DOM. It is
very busy and can quickly overwhelm the memory allocated to a
browser tab.
A full, working proof-of-concept JavaScript application is available
:blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`.
It can be viewed by pointing a browser at the ``/app`` endpoint in a
running ``rest_cherrypy`` instance.
Or using CORS:
.. code-block:: javascript
var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true});
It is also possible to consume the stream via the shell.
Records are separated by blank lines; the ``data:`` and ``tag:``
prefixes will need to be removed manually before attempting to
unserialize the JSON.
curl's ``-N`` flag turns off input buffering which is required to
process the stream incrementally.
Here is a basic example of printing each event as it comes in:
.. code-block:: bash
curl -NsS localhost:8000/events |\
while IFS= read -r line ; do
echo $line
done
Here is an example of using awk to filter events based on tag:
.. code-block:: bash
curl -NsS localhost:8000/events |\
awk '
BEGIN { RS=""; FS="\\n" }
$1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 }
'
tag: salt/job/20140112010149808995/new
data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}}
tag: 20140112010149808995
data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}}
'''
cookies = cherrypy.request.cookie
auth_token = token or salt_token or (
cookies['session_id'].value if 'session_id' in cookies else None)
if not self._is_valid_token(auth_token):
raise cherrypy.HTTPError(401)
# Release the session lock before starting the long-running response
cherrypy.session.release_lock()
cherrypy.response.headers['Content-Type'] = 'text/event-stream'
cherrypy.response.headers['Cache-Control'] = 'no-cache'
cherrypy.response.headers['Connection'] = 'keep-alive'
def listen():
'''
An iterator to yield Salt events
'''
event = salt.utils.event.get_event(
'master',
sock_dir=self.opts['sock_dir'],
transport=self.opts['transport'],
opts=self.opts,
listen=True)
stream = event.iter_events(full=True, auto_reconnect=True)
yield str('retry: 400\n') # future lint: disable=blacklisted-function
while True:
data = next(stream)
yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function
yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function
return listen() | python | def GET(self, token=None, salt_token=None):
r'''
An HTTP stream of the Salt master event bus
This stream is formatted per the Server Sent Events (SSE) spec. Each
event is formatted as JSON.
.. http:get:: /events
:status 200: |200|
:status 401: |401|
:status 406: |406|
:query token: **optional** parameter containing the token
ordinarily supplied via the X-Auth-Token header in order to
allow cross-domain requests in browsers that do not include
CORS support in the EventSource API. E.g.,
``curl -NsS localhost:8000/events?token=308650d``
:query salt_token: **optional** parameter containing a raw Salt
*eauth token* (not to be confused with the token returned from
the /login URL). E.g.,
``curl -NsS localhost:8000/events?salt_token=30742765``
**Example request:**
.. code-block:: bash
curl -NsS localhost:8000/events
.. code-block:: text
GET /events HTTP/1.1
Host: localhost:8000
**Example response:**
Note, the ``tag`` field is not part of the spec. SSE compliant clients
should ignore unknown fields. This addition allows non-compliant
clients to only watch for certain tags without having to deserialze the
JSON object each time.
.. code-block:: text
HTTP/1.1 200 OK
Connection: keep-alive
Cache-Control: no-cache
Content-Type: text/event-stream;charset=utf-8
retry: 400
tag: salt/job/20130802115730568475/new
data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}}
tag: salt/job/20130802115730568475/ret/jerry
data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}}
The event stream can be easily consumed via JavaScript:
.. code-block:: javascript
var source = new EventSource('/events');
source.onopen = function() { console.info('Listening ...') };
source.onerror = function(err) { console.error(err) };
source.onmessage = function(message) {
var saltEvent = JSON.parse(message.data);
console.log(saltEvent.tag, saltEvent.data);
};
Note, the SSE stream is fast and completely asynchronous and Salt is
very fast. If a job is created using a regular POST request, it is
possible that the job return will be available on the SSE stream before
the response for the POST request arrives. It is important to take that
asynchronicity into account when designing an application. Below are
some general guidelines.
* Subscribe to the SSE stream _before_ creating any events.
* Process SSE events directly as they arrive and don't wait for any
other process to "complete" first (like an ajax request).
* Keep a buffer of events if the event stream must be used for
synchronous lookups.
* Be cautious in writing Salt's event stream directly to the DOM. It is
very busy and can quickly overwhelm the memory allocated to a
browser tab.
A full, working proof-of-concept JavaScript application is available
:blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`.
It can be viewed by pointing a browser at the ``/app`` endpoint in a
running ``rest_cherrypy`` instance.
Or using CORS:
.. code-block:: javascript
var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true});
It is also possible to consume the stream via the shell.
Records are separated by blank lines; the ``data:`` and ``tag:``
prefixes will need to be removed manually before attempting to
unserialize the JSON.
curl's ``-N`` flag turns off input buffering which is required to
process the stream incrementally.
Here is a basic example of printing each event as it comes in:
.. code-block:: bash
curl -NsS localhost:8000/events |\
while IFS= read -r line ; do
echo $line
done
Here is an example of using awk to filter events based on tag:
.. code-block:: bash
curl -NsS localhost:8000/events |\
awk '
BEGIN { RS=""; FS="\\n" }
$1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 }
'
tag: salt/job/20140112010149808995/new
data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}}
tag: 20140112010149808995
data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}}
'''
cookies = cherrypy.request.cookie
auth_token = token or salt_token or (
cookies['session_id'].value if 'session_id' in cookies else None)
if not self._is_valid_token(auth_token):
raise cherrypy.HTTPError(401)
# Release the session lock before starting the long-running response
cherrypy.session.release_lock()
cherrypy.response.headers['Content-Type'] = 'text/event-stream'
cherrypy.response.headers['Cache-Control'] = 'no-cache'
cherrypy.response.headers['Connection'] = 'keep-alive'
def listen():
'''
An iterator to yield Salt events
'''
event = salt.utils.event.get_event(
'master',
sock_dir=self.opts['sock_dir'],
transport=self.opts['transport'],
opts=self.opts,
listen=True)
stream = event.iter_events(full=True, auto_reconnect=True)
yield str('retry: 400\n') # future lint: disable=blacklisted-function
while True:
data = next(stream)
yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function
yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function
return listen() | [
"def",
"GET",
"(",
"self",
",",
"token",
"=",
"None",
",",
"salt_token",
"=",
"None",
")",
":",
"cookies",
"=",
"cherrypy",
".",
"request",
".",
"cookie",
"auth_token",
"=",
"token",
"or",
"salt_token",
"or",
"(",
"cookies",
"[",
"'session_id'",
"]",
"... | r'''
An HTTP stream of the Salt master event bus
This stream is formatted per the Server Sent Events (SSE) spec. Each
event is formatted as JSON.
.. http:get:: /events
:status 200: |200|
:status 401: |401|
:status 406: |406|
:query token: **optional** parameter containing the token
ordinarily supplied via the X-Auth-Token header in order to
allow cross-domain requests in browsers that do not include
CORS support in the EventSource API. E.g.,
``curl -NsS localhost:8000/events?token=308650d``
:query salt_token: **optional** parameter containing a raw Salt
*eauth token* (not to be confused with the token returned from
the /login URL). E.g.,
``curl -NsS localhost:8000/events?salt_token=30742765``
**Example request:**
.. code-block:: bash
curl -NsS localhost:8000/events
.. code-block:: text
GET /events HTTP/1.1
Host: localhost:8000
**Example response:**
Note, the ``tag`` field is not part of the spec. SSE compliant clients
should ignore unknown fields. This addition allows non-compliant
clients to only watch for certain tags without having to deserialze the
JSON object each time.
.. code-block:: text
HTTP/1.1 200 OK
Connection: keep-alive
Cache-Control: no-cache
Content-Type: text/event-stream;charset=utf-8
retry: 400
tag: salt/job/20130802115730568475/new
data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}}
tag: salt/job/20130802115730568475/ret/jerry
data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}}
The event stream can be easily consumed via JavaScript:
.. code-block:: javascript
var source = new EventSource('/events');
source.onopen = function() { console.info('Listening ...') };
source.onerror = function(err) { console.error(err) };
source.onmessage = function(message) {
var saltEvent = JSON.parse(message.data);
console.log(saltEvent.tag, saltEvent.data);
};
Note, the SSE stream is fast and completely asynchronous and Salt is
very fast. If a job is created using a regular POST request, it is
possible that the job return will be available on the SSE stream before
the response for the POST request arrives. It is important to take that
asynchronicity into account when designing an application. Below are
some general guidelines.
* Subscribe to the SSE stream _before_ creating any events.
* Process SSE events directly as they arrive and don't wait for any
other process to "complete" first (like an ajax request).
* Keep a buffer of events if the event stream must be used for
synchronous lookups.
* Be cautious in writing Salt's event stream directly to the DOM. It is
very busy and can quickly overwhelm the memory allocated to a
browser tab.
A full, working proof-of-concept JavaScript application is available
:blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`.
It can be viewed by pointing a browser at the ``/app`` endpoint in a
running ``rest_cherrypy`` instance.
Or using CORS:
.. code-block:: javascript
var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true});
It is also possible to consume the stream via the shell.
Records are separated by blank lines; the ``data:`` and ``tag:``
prefixes will need to be removed manually before attempting to
unserialize the JSON.
curl's ``-N`` flag turns off input buffering which is required to
process the stream incrementally.
Here is a basic example of printing each event as it comes in:
.. code-block:: bash
curl -NsS localhost:8000/events |\
while IFS= read -r line ; do
echo $line
done
Here is an example of using awk to filter events based on tag:
.. code-block:: bash
curl -NsS localhost:8000/events |\
awk '
BEGIN { RS=""; FS="\\n" }
$1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 }
'
tag: salt/job/20140112010149808995/new
data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}}
tag: 20140112010149808995
data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} | [
"r",
"An",
"HTTP",
"stream",
"of",
"the",
"Salt",
"master",
"event",
"bus"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2221-L2380 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | WebsocketEndpoint.GET | def GET(self, token=None, **kwargs):
'''
Return a websocket connection of Salt's event stream
.. http:get:: /ws/(token)
:query format_events: The event stream will undergo server-side
formatting if the ``format_events`` URL parameter is included
in the request. This can be useful to avoid formatting on the
client-side:
.. code-block:: bash
curl -NsS <...snip...> localhost:8000/ws?format_events
:reqheader X-Auth-Token: an authentication token from
:py:class:`~Login`.
:status 101: switching to the websockets protocol
:status 401: |401|
:status 406: |406|
**Example request:** ::
curl -NsSk \\
-H 'X-Auth-Token: ffedf49d' \\
-H 'Host: localhost:8000' \\
-H 'Connection: Upgrade' \\
-H 'Upgrade: websocket' \\
-H 'Origin: https://localhost:8000' \\
-H 'Sec-WebSocket-Version: 13' \\
-H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\
localhost:8000/ws
.. code-block:: text
GET /ws HTTP/1.1
Connection: Upgrade
Upgrade: websocket
Host: localhost:8000
Origin: https://localhost:8000
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA==
X-Auth-Token: ffedf49d
**Example response**:
.. code-block:: text
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE=
Sec-WebSocket-Version: 13
An authentication token **may optionally** be passed as part of the URL
for browsers that cannot be configured to send the authentication
header or cookie:
.. code-block:: bash
curl -NsS <...snip...> localhost:8000/ws/ffedf49d
The event stream can be easily consumed via JavaScript:
.. code-block:: javascript
// Note, you must be authenticated!
var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a');
source.onerror = function(e) { console.debug('error!', e); };
source.onmessage = function(e) { console.debug(e.data); };
source.send('websocket client ready')
source.close();
Or via Python, using the Python module `websocket-client
<https://pypi.python.org/pypi/websocket-client/>`_ for example.
.. code-block:: python
# Note, you must be authenticated!
from websocket import create_connection
ws = create_connection('ws://localhost:8000/ws/d0ce6c1a')
ws.send('websocket client ready')
# Look at https://pypi.python.org/pypi/websocket-client/ for more
# examples.
while listening_to_events:
print ws.recv()
ws.close()
Above examples show how to establish a websocket connection to Salt and
activating real time updates from Salt's event stream by signaling
``websocket client ready``.
'''
# Pulling the session token from an URL param is a workaround for
# browsers not supporting CORS in the EventSource API.
if token:
orig_session, _ = cherrypy.session.cache.get(token, ({}, None))
salt_token = orig_session.get('token')
else:
salt_token = cherrypy.session.get('token')
# Manually verify the token
if not salt_token or not self.auth.get_tok(salt_token):
raise cherrypy.HTTPError(401)
# Release the session lock before starting the long-running response
cherrypy.session.release_lock()
# A handler is the server side end of the websocket connection. Each
# request spawns a new instance of this handler
handler = cherrypy.request.ws_handler
def event_stream(handler, pipe):
'''
An iterator to return Salt events (and optionally format them)
'''
# blocks until send is called on the parent end of this pipe.
pipe.recv()
event = salt.utils.event.get_event(
'master',
sock_dir=self.opts['sock_dir'],
transport=self.opts['transport'],
opts=self.opts,
listen=True)
stream = event.iter_events(full=True, auto_reconnect=True)
SaltInfo = event_processor.SaltInfo(handler)
def signal_handler(signal, frame):
os._exit(0)
signal.signal(signal.SIGTERM, signal_handler)
while True:
data = next(stream)
if data:
try: # work around try to decode catch unicode errors
if 'format_events' in kwargs:
SaltInfo.process(data, salt_token, self.opts)
else:
handler.send(
str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function
False
)
except UnicodeDecodeError:
logger.error(
"Error: Salt event has non UTF-8 data:\n%s", data)
parent_pipe, child_pipe = Pipe()
handler.pipe = parent_pipe
handler.opts = self.opts
# Process to handle asynchronous push to a client.
# Each GET request causes a process to be kicked off.
proc = Process(target=event_stream, args=(handler, child_pipe))
proc.start() | python | def GET(self, token=None, **kwargs):
'''
Return a websocket connection of Salt's event stream
.. http:get:: /ws/(token)
:query format_events: The event stream will undergo server-side
formatting if the ``format_events`` URL parameter is included
in the request. This can be useful to avoid formatting on the
client-side:
.. code-block:: bash
curl -NsS <...snip...> localhost:8000/ws?format_events
:reqheader X-Auth-Token: an authentication token from
:py:class:`~Login`.
:status 101: switching to the websockets protocol
:status 401: |401|
:status 406: |406|
**Example request:** ::
curl -NsSk \\
-H 'X-Auth-Token: ffedf49d' \\
-H 'Host: localhost:8000' \\
-H 'Connection: Upgrade' \\
-H 'Upgrade: websocket' \\
-H 'Origin: https://localhost:8000' \\
-H 'Sec-WebSocket-Version: 13' \\
-H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\
localhost:8000/ws
.. code-block:: text
GET /ws HTTP/1.1
Connection: Upgrade
Upgrade: websocket
Host: localhost:8000
Origin: https://localhost:8000
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA==
X-Auth-Token: ffedf49d
**Example response**:
.. code-block:: text
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE=
Sec-WebSocket-Version: 13
An authentication token **may optionally** be passed as part of the URL
for browsers that cannot be configured to send the authentication
header or cookie:
.. code-block:: bash
curl -NsS <...snip...> localhost:8000/ws/ffedf49d
The event stream can be easily consumed via JavaScript:
.. code-block:: javascript
// Note, you must be authenticated!
var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a');
source.onerror = function(e) { console.debug('error!', e); };
source.onmessage = function(e) { console.debug(e.data); };
source.send('websocket client ready')
source.close();
Or via Python, using the Python module `websocket-client
<https://pypi.python.org/pypi/websocket-client/>`_ for example.
.. code-block:: python
# Note, you must be authenticated!
from websocket import create_connection
ws = create_connection('ws://localhost:8000/ws/d0ce6c1a')
ws.send('websocket client ready')
# Look at https://pypi.python.org/pypi/websocket-client/ for more
# examples.
while listening_to_events:
print ws.recv()
ws.close()
Above examples show how to establish a websocket connection to Salt and
activating real time updates from Salt's event stream by signaling
``websocket client ready``.
'''
# Pulling the session token from an URL param is a workaround for
# browsers not supporting CORS in the EventSource API.
if token:
orig_session, _ = cherrypy.session.cache.get(token, ({}, None))
salt_token = orig_session.get('token')
else:
salt_token = cherrypy.session.get('token')
# Manually verify the token
if not salt_token or not self.auth.get_tok(salt_token):
raise cherrypy.HTTPError(401)
# Release the session lock before starting the long-running response
cherrypy.session.release_lock()
# A handler is the server side end of the websocket connection. Each
# request spawns a new instance of this handler
handler = cherrypy.request.ws_handler
def event_stream(handler, pipe):
'''
An iterator to return Salt events (and optionally format them)
'''
# blocks until send is called on the parent end of this pipe.
pipe.recv()
event = salt.utils.event.get_event(
'master',
sock_dir=self.opts['sock_dir'],
transport=self.opts['transport'],
opts=self.opts,
listen=True)
stream = event.iter_events(full=True, auto_reconnect=True)
SaltInfo = event_processor.SaltInfo(handler)
def signal_handler(signal, frame):
os._exit(0)
signal.signal(signal.SIGTERM, signal_handler)
while True:
data = next(stream)
if data:
try: # work around try to decode catch unicode errors
if 'format_events' in kwargs:
SaltInfo.process(data, salt_token, self.opts)
else:
handler.send(
str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function
False
)
except UnicodeDecodeError:
logger.error(
"Error: Salt event has non UTF-8 data:\n%s", data)
parent_pipe, child_pipe = Pipe()
handler.pipe = parent_pipe
handler.opts = self.opts
# Process to handle asynchronous push to a client.
# Each GET request causes a process to be kicked off.
proc = Process(target=event_stream, args=(handler, child_pipe))
proc.start() | [
"def",
"GET",
"(",
"self",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Pulling the session token from an URL param is a workaround for",
"# browsers not supporting CORS in the EventSource API.",
"if",
"token",
":",
"orig_session",
",",
"_",
"=",
"ch... | Return a websocket connection of Salt's event stream
.. http:get:: /ws/(token)
:query format_events: The event stream will undergo server-side
formatting if the ``format_events`` URL parameter is included
in the request. This can be useful to avoid formatting on the
client-side:
.. code-block:: bash
curl -NsS <...snip...> localhost:8000/ws?format_events
:reqheader X-Auth-Token: an authentication token from
:py:class:`~Login`.
:status 101: switching to the websockets protocol
:status 401: |401|
:status 406: |406|
**Example request:** ::
curl -NsSk \\
-H 'X-Auth-Token: ffedf49d' \\
-H 'Host: localhost:8000' \\
-H 'Connection: Upgrade' \\
-H 'Upgrade: websocket' \\
-H 'Origin: https://localhost:8000' \\
-H 'Sec-WebSocket-Version: 13' \\
-H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\
localhost:8000/ws
.. code-block:: text
GET /ws HTTP/1.1
Connection: Upgrade
Upgrade: websocket
Host: localhost:8000
Origin: https://localhost:8000
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA==
X-Auth-Token: ffedf49d
**Example response**:
.. code-block:: text
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE=
Sec-WebSocket-Version: 13
An authentication token **may optionally** be passed as part of the URL
for browsers that cannot be configured to send the authentication
header or cookie:
.. code-block:: bash
curl -NsS <...snip...> localhost:8000/ws/ffedf49d
The event stream can be easily consumed via JavaScript:
.. code-block:: javascript
// Note, you must be authenticated!
var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a');
source.onerror = function(e) { console.debug('error!', e); };
source.onmessage = function(e) { console.debug(e.data); };
source.send('websocket client ready')
source.close();
Or via Python, using the Python module `websocket-client
<https://pypi.python.org/pypi/websocket-client/>`_ for example.
.. code-block:: python
# Note, you must be authenticated!
from websocket import create_connection
ws = create_connection('ws://localhost:8000/ws/d0ce6c1a')
ws.send('websocket client ready')
# Look at https://pypi.python.org/pypi/websocket-client/ for more
# examples.
while listening_to_events:
print ws.recv()
ws.close()
Above examples show how to establish a websocket connection to Salt and
activating real time updates from Salt's event stream by signaling
``websocket client ready``. | [
"Return",
"a",
"websocket",
"connection",
"of",
"Salt",
"s",
"event",
"stream"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2413-L2573 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | Webhook.POST | def POST(self, *args, **kwargs):
'''
Fire an event in Salt with a custom event tag and data
.. http:post:: /hook
:status 200: |200|
:status 401: |401|
:status 406: |406|
:status 413: request body is too large
**Example request:**
.. code-block:: bash
curl -sS localhost:8000/hook \\
-H 'Content-type: application/json' \\
-d '{"foo": "Foo!", "bar": "Bar!"}'
.. code-block:: text
POST /hook HTTP/1.1
Host: localhost:8000
Content-Length: 16
Content-Type: application/json
{"foo": "Foo!", "bar": "Bar!"}
**Example response**:
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 14
Content-Type: application/json
{"success": true}
As a practical example, an internal continuous-integration build
server could send an HTTP POST request to the URL
``https://localhost:8000/hook/mycompany/build/success`` which contains
the result of a build and the SHA of the version that was built as
JSON. That would then produce the following event in Salt that could be
used to kick off a deployment via Salt's Reactor::
Event fired at Fri Feb 14 17:40:11 2014
*************************
Tag: salt/netapi/hook/mycompany/build/success
Data:
{'_stamp': '2014-02-14_17:40:11.440996',
'headers': {
'X-My-Secret-Key': 'F0fAgoQjIT@W',
'Content-Length': '37',
'Content-Type': 'application/json',
'Host': 'localhost:8000',
'Remote-Addr': '127.0.0.1'},
'post': {'revision': 'aa22a3c4b2e7', 'result': True}}
Salt's Reactor could listen for the event:
.. code-block:: yaml
reactor:
- 'salt/netapi/hook/mycompany/build/*':
- /srv/reactor/react_ci_builds.sls
And finally deploy the new build:
.. code-block:: jinja
{% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %}
{% set build = data.get('post', {}) %}
{% if secret_key == 'F0fAgoQjIT@W' and build.result == True %}
deploy_my_app:
cmd.state.sls:
- tgt: 'application*'
- arg:
- myapp.deploy
- kwarg:
pillar:
revision: {{ revision }}
{% endif %}
'''
tag = '/'.join(itertools.chain(self.tag_base, args))
data = cherrypy.serving.request.unserialized_data
if not data:
data = {}
raw_body = getattr(cherrypy.serving.request, 'raw_body', '')
headers = dict(cherrypy.request.headers)
ret = self.event.fire_event({
'body': raw_body,
'post': data,
'headers': headers,
}, tag)
return {'success': ret} | python | def POST(self, *args, **kwargs):
'''
Fire an event in Salt with a custom event tag and data
.. http:post:: /hook
:status 200: |200|
:status 401: |401|
:status 406: |406|
:status 413: request body is too large
**Example request:**
.. code-block:: bash
curl -sS localhost:8000/hook \\
-H 'Content-type: application/json' \\
-d '{"foo": "Foo!", "bar": "Bar!"}'
.. code-block:: text
POST /hook HTTP/1.1
Host: localhost:8000
Content-Length: 16
Content-Type: application/json
{"foo": "Foo!", "bar": "Bar!"}
**Example response**:
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 14
Content-Type: application/json
{"success": true}
As a practical example, an internal continuous-integration build
server could send an HTTP POST request to the URL
``https://localhost:8000/hook/mycompany/build/success`` which contains
the result of a build and the SHA of the version that was built as
JSON. That would then produce the following event in Salt that could be
used to kick off a deployment via Salt's Reactor::
Event fired at Fri Feb 14 17:40:11 2014
*************************
Tag: salt/netapi/hook/mycompany/build/success
Data:
{'_stamp': '2014-02-14_17:40:11.440996',
'headers': {
'X-My-Secret-Key': 'F0fAgoQjIT@W',
'Content-Length': '37',
'Content-Type': 'application/json',
'Host': 'localhost:8000',
'Remote-Addr': '127.0.0.1'},
'post': {'revision': 'aa22a3c4b2e7', 'result': True}}
Salt's Reactor could listen for the event:
.. code-block:: yaml
reactor:
- 'salt/netapi/hook/mycompany/build/*':
- /srv/reactor/react_ci_builds.sls
And finally deploy the new build:
.. code-block:: jinja
{% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %}
{% set build = data.get('post', {}) %}
{% if secret_key == 'F0fAgoQjIT@W' and build.result == True %}
deploy_my_app:
cmd.state.sls:
- tgt: 'application*'
- arg:
- myapp.deploy
- kwarg:
pillar:
revision: {{ revision }}
{% endif %}
'''
tag = '/'.join(itertools.chain(self.tag_base, args))
data = cherrypy.serving.request.unserialized_data
if not data:
data = {}
raw_body = getattr(cherrypy.serving.request, 'raw_body', '')
headers = dict(cherrypy.request.headers)
ret = self.event.fire_event({
'body': raw_body,
'post': data,
'headers': headers,
}, tag)
return {'success': ret} | [
"def",
"POST",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tag",
"=",
"'/'",
".",
"join",
"(",
"itertools",
".",
"chain",
"(",
"self",
".",
"tag_base",
",",
"args",
")",
")",
"data",
"=",
"cherrypy",
".",
"serving",
".",
... | Fire an event in Salt with a custom event tag and data
.. http:post:: /hook
:status 200: |200|
:status 401: |401|
:status 406: |406|
:status 413: request body is too large
**Example request:**
.. code-block:: bash
curl -sS localhost:8000/hook \\
-H 'Content-type: application/json' \\
-d '{"foo": "Foo!", "bar": "Bar!"}'
.. code-block:: text
POST /hook HTTP/1.1
Host: localhost:8000
Content-Length: 16
Content-Type: application/json
{"foo": "Foo!", "bar": "Bar!"}
**Example response**:
.. code-block:: text
HTTP/1.1 200 OK
Content-Length: 14
Content-Type: application/json
{"success": true}
As a practical example, an internal continuous-integration build
server could send an HTTP POST request to the URL
``https://localhost:8000/hook/mycompany/build/success`` which contains
the result of a build and the SHA of the version that was built as
JSON. That would then produce the following event in Salt that could be
used to kick off a deployment via Salt's Reactor::
Event fired at Fri Feb 14 17:40:11 2014
*************************
Tag: salt/netapi/hook/mycompany/build/success
Data:
{'_stamp': '2014-02-14_17:40:11.440996',
'headers': {
'X-My-Secret-Key': 'F0fAgoQjIT@W',
'Content-Length': '37',
'Content-Type': 'application/json',
'Host': 'localhost:8000',
'Remote-Addr': '127.0.0.1'},
'post': {'revision': 'aa22a3c4b2e7', 'result': True}}
Salt's Reactor could listen for the event:
.. code-block:: yaml
reactor:
- 'salt/netapi/hook/mycompany/build/*':
- /srv/reactor/react_ci_builds.sls
And finally deploy the new build:
.. code-block:: jinja
{% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %}
{% set build = data.get('post', {}) %}
{% if secret_key == 'F0fAgoQjIT@W' and build.result == True %}
deploy_my_app:
cmd.state.sls:
- tgt: 'application*'
- arg:
- myapp.deploy
- kwarg:
pillar:
revision: {{ revision }}
{% endif %} | [
"Fire",
"an",
"event",
"in",
"Salt",
"with",
"a",
"custom",
"event",
"tag",
"and",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2643-L2739 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | App.GET | def GET(self, *args):
'''
Serve a single static file ignoring the remaining path
This is useful in combination with a browser-based app using the HTML5
history API.
.. http::get:: /app
:reqheader X-Auth-Token: |req_token|
:status 200: |200|
:status 401: |401|
'''
apiopts = cherrypy.config['apiopts']
default_index = os.path.abspath(os.path.join(
os.path.dirname(__file__), 'index.html'))
return cherrypy.lib.static.serve_file(
apiopts.get('app', default_index)) | python | def GET(self, *args):
'''
Serve a single static file ignoring the remaining path
This is useful in combination with a browser-based app using the HTML5
history API.
.. http::get:: /app
:reqheader X-Auth-Token: |req_token|
:status 200: |200|
:status 401: |401|
'''
apiopts = cherrypy.config['apiopts']
default_index = os.path.abspath(os.path.join(
os.path.dirname(__file__), 'index.html'))
return cherrypy.lib.static.serve_file(
apiopts.get('app', default_index)) | [
"def",
"GET",
"(",
"self",
",",
"*",
"args",
")",
":",
"apiopts",
"=",
"cherrypy",
".",
"config",
"[",
"'apiopts'",
"]",
"default_index",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"d... | Serve a single static file ignoring the remaining path
This is useful in combination with a browser-based app using the HTML5
history API.
.. http::get:: /app
:reqheader X-Auth-Token: |req_token|
:status 200: |200|
:status 401: |401| | [
"Serve",
"a",
"single",
"static",
"file",
"ignoring",
"the",
"remaining",
"path"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2783-L2803 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | API._setattr_url_map | def _setattr_url_map(self):
'''
Set an attribute on the local instance for each key/val in url_map
CherryPy uses class attributes to resolve URLs.
'''
if self.apiopts.get('enable_sessions', True) is False:
url_blacklist = ['login', 'logout', 'minions', 'jobs']
else:
url_blacklist = []
urls = ((url, cls) for url, cls in six.iteritems(self.url_map)
if url not in url_blacklist)
for url, cls in urls:
setattr(self, url, cls()) | python | def _setattr_url_map(self):
'''
Set an attribute on the local instance for each key/val in url_map
CherryPy uses class attributes to resolve URLs.
'''
if self.apiopts.get('enable_sessions', True) is False:
url_blacklist = ['login', 'logout', 'minions', 'jobs']
else:
url_blacklist = []
urls = ((url, cls) for url, cls in six.iteritems(self.url_map)
if url not in url_blacklist)
for url, cls in urls:
setattr(self, url, cls()) | [
"def",
"_setattr_url_map",
"(",
"self",
")",
":",
"if",
"self",
".",
"apiopts",
".",
"get",
"(",
"'enable_sessions'",
",",
"True",
")",
"is",
"False",
":",
"url_blacklist",
"=",
"[",
"'login'",
",",
"'logout'",
",",
"'minions'",
",",
"'jobs'",
"]",
"else... | Set an attribute on the local instance for each key/val in url_map
CherryPy uses class attributes to resolve URLs. | [
"Set",
"an",
"attribute",
"on",
"the",
"local",
"instance",
"for",
"each",
"key",
"/",
"val",
"in",
"url_map"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2823-L2838 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | API._update_url_map | def _update_url_map(self):
'''
Assemble any dynamic or configurable URLs
'''
if HAS_WEBSOCKETS:
self.url_map.update({
'ws': WebsocketEndpoint,
})
# Allow the Webhook URL to be overridden from the conf.
self.url_map.update({
self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook,
})
# Enable the single-page JS app URL.
self.url_map.update({
self.apiopts.get('app_path', 'app').lstrip('/'): App,
}) | python | def _update_url_map(self):
'''
Assemble any dynamic or configurable URLs
'''
if HAS_WEBSOCKETS:
self.url_map.update({
'ws': WebsocketEndpoint,
})
# Allow the Webhook URL to be overridden from the conf.
self.url_map.update({
self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook,
})
# Enable the single-page JS app URL.
self.url_map.update({
self.apiopts.get('app_path', 'app').lstrip('/'): App,
}) | [
"def",
"_update_url_map",
"(",
"self",
")",
":",
"if",
"HAS_WEBSOCKETS",
":",
"self",
".",
"url_map",
".",
"update",
"(",
"{",
"'ws'",
":",
"WebsocketEndpoint",
",",
"}",
")",
"# Allow the Webhook URL to be overridden from the conf.",
"self",
".",
"url_map",
".",
... | Assemble any dynamic or configurable URLs | [
"Assemble",
"any",
"dynamic",
"or",
"configurable",
"URLs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2840-L2857 | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | API.get_conf | def get_conf(self):
'''
Combine the CherryPy configuration with the rest_cherrypy config values
pulled from the master config and return the CherryPy configuration
'''
conf = {
'global': {
'server.socket_host': self.apiopts.get('host', '0.0.0.0'),
'server.socket_port': self.apiopts.get('port', 8000),
'server.thread_pool': self.apiopts.get('thread_pool', 100),
'server.socket_queue_size': self.apiopts.get('queue_size', 30),
'max_request_body_size': self.apiopts.get(
'max_request_body_size', 1048576),
'debug': self.apiopts.get('debug', False),
'log.access_file': self.apiopts.get('log_access_file', ''),
'log.error_file': self.apiopts.get('log_error_file', ''),
},
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.trailing_slash.on': True,
'tools.gzip.on': True,
'tools.html_override.on': True,
'tools.cors_tool.on': True,
},
}
if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0:
# CherryPy >= 12.0 no longer supports "timeout_monitor", only set
# this config option when using an older version of CherryPy.
# See Issue #44601 for more information.
conf['global']['engine.timeout_monitor.on'] = self.apiopts.get(
'expire_responses', True
)
if cpstats and self.apiopts.get('collect_stats', False):
conf['/']['tools.cpstats.on'] = True
if 'favicon' in self.apiopts:
conf['/favicon.ico'] = {
'tools.staticfile.on': True,
'tools.staticfile.filename': self.apiopts['favicon'],
}
if self.apiopts.get('debug', False) is False:
conf['global']['environment'] = 'production'
# Serve static media if the directory has been set in the configuration
if 'static' in self.apiopts:
conf[self.apiopts.get('static_path', '/static')] = {
'tools.staticdir.on': True,
'tools.staticdir.dir': self.apiopts['static'],
}
# Add to global config
cherrypy.config.update(conf['global'])
return conf | python | def get_conf(self):
'''
Combine the CherryPy configuration with the rest_cherrypy config values
pulled from the master config and return the CherryPy configuration
'''
conf = {
'global': {
'server.socket_host': self.apiopts.get('host', '0.0.0.0'),
'server.socket_port': self.apiopts.get('port', 8000),
'server.thread_pool': self.apiopts.get('thread_pool', 100),
'server.socket_queue_size': self.apiopts.get('queue_size', 30),
'max_request_body_size': self.apiopts.get(
'max_request_body_size', 1048576),
'debug': self.apiopts.get('debug', False),
'log.access_file': self.apiopts.get('log_access_file', ''),
'log.error_file': self.apiopts.get('log_error_file', ''),
},
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.trailing_slash.on': True,
'tools.gzip.on': True,
'tools.html_override.on': True,
'tools.cors_tool.on': True,
},
}
if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0:
# CherryPy >= 12.0 no longer supports "timeout_monitor", only set
# this config option when using an older version of CherryPy.
# See Issue #44601 for more information.
conf['global']['engine.timeout_monitor.on'] = self.apiopts.get(
'expire_responses', True
)
if cpstats and self.apiopts.get('collect_stats', False):
conf['/']['tools.cpstats.on'] = True
if 'favicon' in self.apiopts:
conf['/favicon.ico'] = {
'tools.staticfile.on': True,
'tools.staticfile.filename': self.apiopts['favicon'],
}
if self.apiopts.get('debug', False) is False:
conf['global']['environment'] = 'production'
# Serve static media if the directory has been set in the configuration
if 'static' in self.apiopts:
conf[self.apiopts.get('static_path', '/static')] = {
'tools.staticdir.on': True,
'tools.staticdir.dir': self.apiopts['static'],
}
# Add to global config
cherrypy.config.update(conf['global'])
return conf | [
"def",
"get_conf",
"(",
"self",
")",
":",
"conf",
"=",
"{",
"'global'",
":",
"{",
"'server.socket_host'",
":",
"self",
".",
"apiopts",
".",
"get",
"(",
"'host'",
",",
"'0.0.0.0'",
")",
",",
"'server.socket_port'",
":",
"self",
".",
"apiopts",
".",
"get",... | Combine the CherryPy configuration with the rest_cherrypy config values
pulled from the master config and return the CherryPy configuration | [
"Combine",
"the",
"CherryPy",
"configuration",
"with",
"the",
"rest_cherrypy",
"config",
"values",
"pulled",
"from",
"the",
"master",
"config",
"and",
"return",
"the",
"CherryPy",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2866-L2924 | train |
saltstack/salt | salt/modules/gentoo_service.py | get_disabled | def get_disabled():
'''
Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
(enabled_services, disabled_services) = _get_service_list(include_enabled=False,
include_disabled=True)
return sorted(disabled_services) | python | def get_disabled():
'''
Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
(enabled_services, disabled_services) = _get_service_list(include_enabled=False,
include_disabled=True)
return sorted(disabled_services) | [
"def",
"get_disabled",
"(",
")",
":",
"(",
"enabled_services",
",",
"disabled_services",
")",
"=",
"_get_service_list",
"(",
"include_enabled",
"=",
"False",
",",
"include_disabled",
"=",
"True",
")",
"return",
"sorted",
"(",
"disabled_services",
")"
] | Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled | [
"Return",
"a",
"set",
"of",
"services",
"that",
"are",
"installed",
"but",
"disabled"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L107-L119 | train |
saltstack/salt | salt/modules/gentoo_service.py | available | def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
'''
(enabled_services, disabled_services) = _get_service_list(include_enabled=True,
include_disabled=True)
return name in enabled_services or name in disabled_services | python | def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
'''
(enabled_services, disabled_services) = _get_service_list(include_enabled=True,
include_disabled=True)
return name in enabled_services or name in disabled_services | [
"def",
"available",
"(",
"name",
")",
":",
"(",
"enabled_services",
",",
"disabled_services",
")",
"=",
"_get_service_list",
"(",
"include_enabled",
"=",
"True",
",",
"include_disabled",
"=",
"True",
")",
"return",
"name",
"in",
"enabled_services",
"or",
"name",... | Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd | [
"Returns",
"True",
"if",
"the",
"specified",
"service",
"is",
"available",
"otherwise",
"returns",
"False",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L122-L135 | train |
saltstack/salt | salt/modules/gentoo_service.py | get_all | def get_all():
'''
Return all available boot services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
(enabled_services, disabled_services) = _get_service_list(include_enabled=True,
include_disabled=True)
enabled_services.update(dict([(s, []) for s in disabled_services]))
return odict.OrderedDict(enabled_services) | python | def get_all():
'''
Return all available boot services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
(enabled_services, disabled_services) = _get_service_list(include_enabled=True,
include_disabled=True)
enabled_services.update(dict([(s, []) for s in disabled_services]))
return odict.OrderedDict(enabled_services) | [
"def",
"get_all",
"(",
")",
":",
"(",
"enabled_services",
",",
"disabled_services",
")",
"=",
"_get_service_list",
"(",
"include_enabled",
"=",
"True",
",",
"include_disabled",
"=",
"True",
")",
"enabled_services",
".",
"update",
"(",
"dict",
"(",
"[",
"(",
... | Return all available boot services
CLI Example:
.. code-block:: bash
salt '*' service.get_all | [
"Return",
"all",
"available",
"boot",
"services"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L153-L166 | train |
saltstack/salt | salt/modules/gentoo_service.py | status | def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Signature to use to find the service via ps
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name> [service signature]
'''
if sig:
return bool(__salt__['status.pid'](sig))
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = _service_cmd(service, 'status')
results[service] = not _ret_code(cmd, ignore_retcode=True)
if contains_globbing:
return results
return results[name] | python | def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Signature to use to find the service via ps
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name> [service signature]
'''
if sig:
return bool(__salt__['status.pid'](sig))
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
cmd = _service_cmd(service, 'status')
results[service] = not _ret_code(cmd, ignore_retcode=True)
if contains_globbing:
return results
return results[name] | [
"def",
"status",
"(",
"name",
",",
"sig",
"=",
"None",
")",
":",
"if",
"sig",
":",
"return",
"bool",
"(",
"__salt__",
"[",
"'status.pid'",
"]",
"(",
"sig",
")",
")",
"contains_globbing",
"=",
"bool",
"(",
"re",
".",
"search",
"(",
"r'\\*|\\?|\\[.+\\]'"... | Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Signature to use to find the service via ps
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name> [service signature] | [
"Return",
"the",
"status",
"for",
"a",
"service",
".",
"If",
"the",
"name",
"contains",
"globbing",
"a",
"dict",
"mapping",
"service",
"name",
"to",
"True",
"/",
"False",
"values",
"is",
"returned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L239-L276 | train |
saltstack/salt | salt/modules/gentoo_service.py | enable | def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name> <runlevels=single-runlevel>
salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]>
'''
if 'runlevels' in kwargs:
requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'],
list) else [kwargs['runlevels']])
enabled_levels, disabled_levels = _enable_delta(name, requested_levels)
commands = []
if disabled_levels:
commands.append(_enable_disable_cmd(name, 'delete', disabled_levels))
if enabled_levels:
commands.append(_enable_disable_cmd(name, 'add', enabled_levels))
if not commands:
return True
else:
commands = [_enable_disable_cmd(name, 'add')]
for cmd in commands:
if _ret_code(cmd):
return False
return True | python | def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name> <runlevels=single-runlevel>
salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]>
'''
if 'runlevels' in kwargs:
requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'],
list) else [kwargs['runlevels']])
enabled_levels, disabled_levels = _enable_delta(name, requested_levels)
commands = []
if disabled_levels:
commands.append(_enable_disable_cmd(name, 'delete', disabled_levels))
if enabled_levels:
commands.append(_enable_disable_cmd(name, 'add', enabled_levels))
if not commands:
return True
else:
commands = [_enable_disable_cmd(name, 'add')]
for cmd in commands:
if _ret_code(cmd):
return False
return True | [
"def",
"enable",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'runlevels'",
"in",
"kwargs",
":",
"requested_levels",
"=",
"set",
"(",
"kwargs",
"[",
"'runlevels'",
"]",
"if",
"isinstance",
"(",
"kwargs",
"[",
"'runlevels'",
"]",
",",
"list",
... | Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name> <runlevels=single-runlevel>
salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]> | [
"Enable",
"the",
"named",
"service",
"to",
"start",
"at",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L279-L306 | train |
saltstack/salt | salt/modules/gentoo_service.py | disable | def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name> <runlevels=single-runlevel>
salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]>
'''
levels = []
if 'runlevels' in kwargs:
requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'],
list) else [kwargs['runlevels']])
levels = _disable_delta(name, requested_levels)
if not levels:
return True
cmd = _enable_disable_cmd(name, 'delete', levels)
return not _ret_code(cmd) | python | def disable(name, **kwargs):
'''
Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name> <runlevels=single-runlevel>
salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]>
'''
levels = []
if 'runlevels' in kwargs:
requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'],
list) else [kwargs['runlevels']])
levels = _disable_delta(name, requested_levels)
if not levels:
return True
cmd = _enable_disable_cmd(name, 'delete', levels)
return not _ret_code(cmd) | [
"def",
"disable",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"levels",
"=",
"[",
"]",
"if",
"'runlevels'",
"in",
"kwargs",
":",
"requested_levels",
"=",
"set",
"(",
"kwargs",
"[",
"'runlevels'",
"]",
"if",
"isinstance",
"(",
"kwargs",
"[",
"'runle... | Disable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name> <runlevels=single-runlevel>
salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]> | [
"Disable",
"the",
"named",
"service",
"to",
"start",
"at",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L309-L328 | train |
saltstack/salt | salt/modules/gentoo_service.py | enabled | def enabled(name, **kwargs):
'''
Return True if the named service is enabled, false otherwise
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name> <runlevels=single-runlevel>
salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]>
'''
enabled_services = get_enabled()
if name not in enabled_services:
return False
if 'runlevels' not in kwargs:
return True
requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'],
list) else [kwargs['runlevels']])
return len(requested_levels - set(enabled_services[name])) == 0 | python | def enabled(name, **kwargs):
'''
Return True if the named service is enabled, false otherwise
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name> <runlevels=single-runlevel>
salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]>
'''
enabled_services = get_enabled()
if name not in enabled_services:
return False
if 'runlevels' not in kwargs:
return True
requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'],
list) else [kwargs['runlevels']])
return len(requested_levels - set(enabled_services[name])) == 0 | [
"def",
"enabled",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"enabled_services",
"=",
"get_enabled",
"(",
")",
"if",
"name",
"not",
"in",
"enabled_services",
":",
"return",
"False",
"if",
"'runlevels'",
"not",
"in",
"kwargs",
":",
"return",
"True",
... | Return True if the named service is enabled, false otherwise
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name> <runlevels=single-runlevel>
salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]> | [
"Return",
"True",
"if",
"the",
"named",
"service",
"is",
"enabled",
"false",
"otherwise"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L331-L349 | train |
saltstack/salt | salt/states/virtualenv_mod.py | managed | def managed(name,
venv_bin=None,
requirements=None,
system_site_packages=False,
distribute=False,
use_wheel=False,
clear=False,
python=None,
extra_search_dir=None,
never_download=None,
prompt=None,
user=None,
cwd=None,
index_url=None,
extra_index_url=None,
pre_releases=False,
no_deps=False,
pip_download=None,
pip_download_cache=None,
pip_exists_action=None,
pip_ignore_installed=False,
proxy=None,
use_vt=False,
env_vars=None,
no_use_wheel=False,
pip_upgrade=False,
pip_pkgs=None,
pip_no_cache_dir=False,
pip_cache_dir=None,
process_dependency_links=False,
no_binary=None,
**kwargs):
'''
Create a virtualenv and optionally manage it with pip
name
Path to the virtualenv.
venv_bin: virtualenv
The name (and optionally path) of the virtualenv command. This can also
be set globally in the minion config file as ``virtualenv.venv_bin``.
requirements: None
Path to a pip requirements file. If the path begins with ``salt://``
the file will be transferred from the master file server.
use_wheel: False
Prefer wheel archives (requires pip >= 1.4).
python : None
Python executable used to build the virtualenv
user: None
The user under which to run virtualenv and pip.
cwd: None
Path to the working directory where `pip install` is executed.
no_deps: False
Pass `--no-deps` to `pip install`.
pip_exists_action: None
Default action of pip when a path already exists: (s)witch, (i)gnore,
(w)ipe, (b)ackup.
proxy: None
Proxy address which is passed to `pip install`.
env_vars: None
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling.
no_use_wheel: False
Force to not use wheel archives (requires pip>=1.4)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or a list of one or more packages
pip_upgrade: False
Pass `--upgrade` to `pip install`.
pip_pkgs: None
As an alternative to `requirements`, pass a list of pip packages that
should be installed.
process_dependency_links: False
Run pip install with the --process_dependency_links flag.
.. versionadded:: 2017.7.0
Also accepts any kwargs that the virtualenv module will. However, some
kwargs, such as the ``pip`` option, require ``- distribute: True``.
.. code-block:: yaml
/var/www/myvirtualenv.com:
virtualenv.managed:
- system_site_packages: False
- requirements: salt://REQUIREMENTS.txt
- env_vars:
PATH_VAR: '/usr/local/bin/'
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'virtualenv.create' not in __salt__:
ret['result'] = False
ret['comment'] = 'Virtualenv was not detected on this system'
return ret
if salt.utils.platform.is_windows():
venv_py = os.path.join(name, 'Scripts', 'python.exe')
else:
venv_py = os.path.join(name, 'bin', 'python')
venv_exists = os.path.exists(venv_py)
# Bail out early if the specified requirements file can't be found
if requirements and requirements.startswith('salt://'):
cached_requirements = __salt__['cp.is_cached'](requirements, __env__)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, __env__
)
# Check if the master version has changed.
if cached_requirements and __salt__['cp.hash_file'](requirements, __env__) != \
__salt__['cp.hash_file'](cached_requirements, __env__):
cached_requirements = __salt__['cp.cache_file'](
requirements, __env__
)
if not cached_requirements:
ret.update({
'result': False,
'comment': 'pip requirements file \'{0}\' not found'.format(
requirements
)
})
return ret
requirements = cached_requirements
# If it already exists, grab the version for posterity
if venv_exists and clear:
ret['changes']['cleared_packages'] = \
__salt__['pip.freeze'](bin_env=name)
ret['changes']['old'] = \
__salt__['cmd.run_stderr']('{0} -V'.format(venv_py)).strip('\n')
# Create (or clear) the virtualenv
if __opts__['test']:
if venv_exists and clear:
ret['result'] = None
ret['comment'] = 'Virtualenv {0} is set to be cleared'.format(name)
return ret
if venv_exists and not clear:
ret['comment'] = 'Virtualenv {0} is already created'.format(name)
return ret
ret['result'] = None
ret['comment'] = 'Virtualenv {0} is set to be created'.format(name)
return ret
if not venv_exists or (venv_exists and clear):
try:
venv_ret = __salt__['virtualenv.create'](
name,
venv_bin=venv_bin,
system_site_packages=system_site_packages,
distribute=distribute,
clear=clear,
python=python,
extra_search_dir=extra_search_dir,
never_download=never_download,
prompt=prompt,
user=user,
use_vt=use_vt,
**kwargs
)
except CommandNotFoundError as err:
ret['result'] = False
ret['comment'] = 'Failed to create virtualenv: {0}'.format(err)
return ret
if venv_ret['retcode'] != 0:
ret['result'] = False
ret['comment'] = venv_ret['stdout'] + venv_ret['stderr']
return ret
ret['result'] = True
ret['changes']['new'] = __salt__['cmd.run_stderr'](
'{0} -V'.format(venv_py)).strip('\n')
if clear:
ret['comment'] = 'Cleared existing virtualenv'
else:
ret['comment'] = 'Created new virtualenv'
elif venv_exists:
ret['comment'] = 'virtualenv exists'
# Check that the pip binary supports the 'use_wheel' option
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
cur_version = __salt__['pip.version'](bin_env=name)
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
ret['result'] = False
ret['comment'] = ('The \'use_wheel\' option is only supported in '
'pip between {0} and {1}. The version of pip detected '
'was {2}.').format(min_version, max_version, cur_version)
return ret
# Check that the pip binary supports the 'no_use_wheel' option
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
cur_version = __salt__['pip.version'](bin_env=name)
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
ret['result'] = False
ret['comment'] = ('The \'no_use_wheel\' option is only supported in '
'pip between {0} and {1}. The version of pip detected '
'was {2}.').format(min_version, max_version, cur_version)
return ret
# Check that the pip binary supports the 'no_binary' option
if no_binary:
min_version = '7.0.0'
cur_version = __salt__['pip.version'](bin_env=name)
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
ret['result'] = False
ret['comment'] = ('The \'no_binary\' option is only supported in '
'pip {0} and newer. The version of pip detected '
'was {1}.').format(min_version, cur_version)
return ret
# Populate the venv via a requirements file
if requirements or pip_pkgs:
try:
before = set(__salt__['pip.freeze'](bin_env=name, user=user, use_vt=use_vt))
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if requirements:
if isinstance(requirements, six.string_types):
req_canary = requirements.split(',')[0]
elif isinstance(requirements, list):
req_canary = requirements[0]
else:
raise TypeError(
'pip requirements must be either a string or a list'
)
if req_canary != os.path.abspath(req_canary):
cwd = os.path.dirname(os.path.abspath(req_canary))
pip_ret = __salt__['pip.install'](
pkgs=pip_pkgs,
requirements=requirements,
process_dependency_links=process_dependency_links,
bin_env=name,
use_wheel=use_wheel,
no_use_wheel=no_use_wheel,
no_binary=no_binary,
user=user,
cwd=cwd,
index_url=index_url,
extra_index_url=extra_index_url,
download=pip_download,
download_cache=pip_download_cache,
pre_releases=pre_releases,
exists_action=pip_exists_action,
ignore_installed=pip_ignore_installed,
upgrade=pip_upgrade,
no_deps=no_deps,
proxy=proxy,
use_vt=use_vt,
env_vars=env_vars,
no_cache_dir=pip_no_cache_dir,
cache_dir=pip_cache_dir,
**kwargs
)
ret['result'] &= pip_ret['retcode'] == 0
if pip_ret['retcode'] > 0:
ret['comment'] = '{0}\n{1}\n{2}'.format(ret['comment'],
pip_ret['stdout'],
pip_ret['stderr'])
after = set(__salt__['pip.freeze'](bin_env=name))
new = list(after - before)
old = list(before - after)
if new or old:
ret['changes']['packages'] = {
'new': new if new else '',
'old': old if old else ''}
return ret | python | def managed(name,
venv_bin=None,
requirements=None,
system_site_packages=False,
distribute=False,
use_wheel=False,
clear=False,
python=None,
extra_search_dir=None,
never_download=None,
prompt=None,
user=None,
cwd=None,
index_url=None,
extra_index_url=None,
pre_releases=False,
no_deps=False,
pip_download=None,
pip_download_cache=None,
pip_exists_action=None,
pip_ignore_installed=False,
proxy=None,
use_vt=False,
env_vars=None,
no_use_wheel=False,
pip_upgrade=False,
pip_pkgs=None,
pip_no_cache_dir=False,
pip_cache_dir=None,
process_dependency_links=False,
no_binary=None,
**kwargs):
'''
Create a virtualenv and optionally manage it with pip
name
Path to the virtualenv.
venv_bin: virtualenv
The name (and optionally path) of the virtualenv command. This can also
be set globally in the minion config file as ``virtualenv.venv_bin``.
requirements: None
Path to a pip requirements file. If the path begins with ``salt://``
the file will be transferred from the master file server.
use_wheel: False
Prefer wheel archives (requires pip >= 1.4).
python : None
Python executable used to build the virtualenv
user: None
The user under which to run virtualenv and pip.
cwd: None
Path to the working directory where `pip install` is executed.
no_deps: False
Pass `--no-deps` to `pip install`.
pip_exists_action: None
Default action of pip when a path already exists: (s)witch, (i)gnore,
(w)ipe, (b)ackup.
proxy: None
Proxy address which is passed to `pip install`.
env_vars: None
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling.
no_use_wheel: False
Force to not use wheel archives (requires pip>=1.4)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or a list of one or more packages
pip_upgrade: False
Pass `--upgrade` to `pip install`.
pip_pkgs: None
As an alternative to `requirements`, pass a list of pip packages that
should be installed.
process_dependency_links: False
Run pip install with the --process_dependency_links flag.
.. versionadded:: 2017.7.0
Also accepts any kwargs that the virtualenv module will. However, some
kwargs, such as the ``pip`` option, require ``- distribute: True``.
.. code-block:: yaml
/var/www/myvirtualenv.com:
virtualenv.managed:
- system_site_packages: False
- requirements: salt://REQUIREMENTS.txt
- env_vars:
PATH_VAR: '/usr/local/bin/'
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'virtualenv.create' not in __salt__:
ret['result'] = False
ret['comment'] = 'Virtualenv was not detected on this system'
return ret
if salt.utils.platform.is_windows():
venv_py = os.path.join(name, 'Scripts', 'python.exe')
else:
venv_py = os.path.join(name, 'bin', 'python')
venv_exists = os.path.exists(venv_py)
# Bail out early if the specified requirements file can't be found
if requirements and requirements.startswith('salt://'):
cached_requirements = __salt__['cp.is_cached'](requirements, __env__)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, __env__
)
# Check if the master version has changed.
if cached_requirements and __salt__['cp.hash_file'](requirements, __env__) != \
__salt__['cp.hash_file'](cached_requirements, __env__):
cached_requirements = __salt__['cp.cache_file'](
requirements, __env__
)
if not cached_requirements:
ret.update({
'result': False,
'comment': 'pip requirements file \'{0}\' not found'.format(
requirements
)
})
return ret
requirements = cached_requirements
# If it already exists, grab the version for posterity
if venv_exists and clear:
ret['changes']['cleared_packages'] = \
__salt__['pip.freeze'](bin_env=name)
ret['changes']['old'] = \
__salt__['cmd.run_stderr']('{0} -V'.format(venv_py)).strip('\n')
# Create (or clear) the virtualenv
if __opts__['test']:
if venv_exists and clear:
ret['result'] = None
ret['comment'] = 'Virtualenv {0} is set to be cleared'.format(name)
return ret
if venv_exists and not clear:
ret['comment'] = 'Virtualenv {0} is already created'.format(name)
return ret
ret['result'] = None
ret['comment'] = 'Virtualenv {0} is set to be created'.format(name)
return ret
if not venv_exists or (venv_exists and clear):
try:
venv_ret = __salt__['virtualenv.create'](
name,
venv_bin=venv_bin,
system_site_packages=system_site_packages,
distribute=distribute,
clear=clear,
python=python,
extra_search_dir=extra_search_dir,
never_download=never_download,
prompt=prompt,
user=user,
use_vt=use_vt,
**kwargs
)
except CommandNotFoundError as err:
ret['result'] = False
ret['comment'] = 'Failed to create virtualenv: {0}'.format(err)
return ret
if venv_ret['retcode'] != 0:
ret['result'] = False
ret['comment'] = venv_ret['stdout'] + venv_ret['stderr']
return ret
ret['result'] = True
ret['changes']['new'] = __salt__['cmd.run_stderr'](
'{0} -V'.format(venv_py)).strip('\n')
if clear:
ret['comment'] = 'Cleared existing virtualenv'
else:
ret['comment'] = 'Created new virtualenv'
elif venv_exists:
ret['comment'] = 'virtualenv exists'
# Check that the pip binary supports the 'use_wheel' option
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
cur_version = __salt__['pip.version'](bin_env=name)
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
ret['result'] = False
ret['comment'] = ('The \'use_wheel\' option is only supported in '
'pip between {0} and {1}. The version of pip detected '
'was {2}.').format(min_version, max_version, cur_version)
return ret
# Check that the pip binary supports the 'no_use_wheel' option
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
cur_version = __salt__['pip.version'](bin_env=name)
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
ret['result'] = False
ret['comment'] = ('The \'no_use_wheel\' option is only supported in '
'pip between {0} and {1}. The version of pip detected '
'was {2}.').format(min_version, max_version, cur_version)
return ret
# Check that the pip binary supports the 'no_binary' option
if no_binary:
min_version = '7.0.0'
cur_version = __salt__['pip.version'](bin_env=name)
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
ret['result'] = False
ret['comment'] = ('The \'no_binary\' option is only supported in '
'pip {0} and newer. The version of pip detected '
'was {1}.').format(min_version, cur_version)
return ret
# Populate the venv via a requirements file
if requirements or pip_pkgs:
try:
before = set(__salt__['pip.freeze'](bin_env=name, user=user, use_vt=use_vt))
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if requirements:
if isinstance(requirements, six.string_types):
req_canary = requirements.split(',')[0]
elif isinstance(requirements, list):
req_canary = requirements[0]
else:
raise TypeError(
'pip requirements must be either a string or a list'
)
if req_canary != os.path.abspath(req_canary):
cwd = os.path.dirname(os.path.abspath(req_canary))
pip_ret = __salt__['pip.install'](
pkgs=pip_pkgs,
requirements=requirements,
process_dependency_links=process_dependency_links,
bin_env=name,
use_wheel=use_wheel,
no_use_wheel=no_use_wheel,
no_binary=no_binary,
user=user,
cwd=cwd,
index_url=index_url,
extra_index_url=extra_index_url,
download=pip_download,
download_cache=pip_download_cache,
pre_releases=pre_releases,
exists_action=pip_exists_action,
ignore_installed=pip_ignore_installed,
upgrade=pip_upgrade,
no_deps=no_deps,
proxy=proxy,
use_vt=use_vt,
env_vars=env_vars,
no_cache_dir=pip_no_cache_dir,
cache_dir=pip_cache_dir,
**kwargs
)
ret['result'] &= pip_ret['retcode'] == 0
if pip_ret['retcode'] > 0:
ret['comment'] = '{0}\n{1}\n{2}'.format(ret['comment'],
pip_ret['stdout'],
pip_ret['stderr'])
after = set(__salt__['pip.freeze'](bin_env=name))
new = list(after - before)
old = list(before - after)
if new or old:
ret['changes']['packages'] = {
'new': new if new else '',
'old': old if old else ''}
return ret | [
"def",
"managed",
"(",
"name",
",",
"venv_bin",
"=",
"None",
",",
"requirements",
"=",
"None",
",",
"system_site_packages",
"=",
"False",
",",
"distribute",
"=",
"False",
",",
"use_wheel",
"=",
"False",
",",
"clear",
"=",
"False",
",",
"python",
"=",
"No... | Create a virtualenv and optionally manage it with pip
name
Path to the virtualenv.
venv_bin: virtualenv
The name (and optionally path) of the virtualenv command. This can also
be set globally in the minion config file as ``virtualenv.venv_bin``.
requirements: None
Path to a pip requirements file. If the path begins with ``salt://``
the file will be transferred from the master file server.
use_wheel: False
Prefer wheel archives (requires pip >= 1.4).
python : None
Python executable used to build the virtualenv
user: None
The user under which to run virtualenv and pip.
cwd: None
Path to the working directory where `pip install` is executed.
no_deps: False
Pass `--no-deps` to `pip install`.
pip_exists_action: None
Default action of pip when a path already exists: (s)witch, (i)gnore,
(w)ipe, (b)ackup.
proxy: None
Proxy address which is passed to `pip install`.
env_vars: None
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling.
no_use_wheel: False
Force to not use wheel archives (requires pip>=1.4)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or a list of one or more packages
pip_upgrade: False
Pass `--upgrade` to `pip install`.
pip_pkgs: None
As an alternative to `requirements`, pass a list of pip packages that
should be installed.
process_dependency_links: False
Run pip install with the --process_dependency_links flag.
.. versionadded:: 2017.7.0
Also accepts any kwargs that the virtualenv module will. However, some
kwargs, such as the ``pip`` option, require ``- distribute: True``.
.. code-block:: yaml
/var/www/myvirtualenv.com:
virtualenv.managed:
- system_site_packages: False
- requirements: salt://REQUIREMENTS.txt
- env_vars:
PATH_VAR: '/usr/local/bin/' | [
"Create",
"a",
"virtualenv",
"and",
"optionally",
"manage",
"it",
"with",
"pip"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virtualenv_mod.py#L33-L337 | train |
saltstack/salt | salt/modules/rh_ip.py | _parse_settings_bond_1 | def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except Exception:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond | python | def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miimon', 'downdelay', 'updelay']:
if binding in opts:
try:
int(opts[binding])
bond.update({binding: opts[binding]})
except Exception:
_raise_error_iface(iface, binding, ['integer'])
else:
_log_default_iface(iface, binding, bond_def[binding])
bond.update({binding: bond_def[binding]})
if 'use_carrier' in opts:
if opts['use_carrier'] in _CONFIG_TRUE:
bond.update({'use_carrier': '1'})
elif opts['use_carrier'] in _CONFIG_FALSE:
bond.update({'use_carrier': '0'})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'use_carrier', valid)
else:
_log_default_iface(iface, 'use_carrier', bond_def['use_carrier'])
bond.update({'use_carrier': bond_def['use_carrier']})
if 'primary' in opts:
bond.update({'primary': opts['primary']})
return bond | [
"def",
"_parse_settings_bond_1",
"(",
"opts",
",",
"iface",
",",
"bond_def",
")",
":",
"bond",
"=",
"{",
"'mode'",
":",
"'1'",
"}",
"for",
"binding",
"in",
"[",
"'miimon'",
",",
"'downdelay'",
",",
"'updelay'",
"]",
":",
"if",
"binding",
"in",
"opts",
... | Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting. | [
"Filters",
"given",
"options",
"and",
"outputs",
"valid",
"settings",
"for",
"bond1",
".",
"If",
"an",
"option",
"has",
"a",
"value",
"that",
"is",
"not",
"expected",
"this",
"function",
"will",
"log",
"what",
"the",
"Interface",
"Setting",
"and",
"what",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L320-L356 | train |
saltstack/salt | salt/modules/rh_ip.py | _parse_settings_vlan | def _parse_settings_vlan(opts, iface):
'''
Filters given options and outputs valid settings for a vlan
'''
vlan = {}
if 'reorder_hdr' in opts:
if opts['reorder_hdr'] in _CONFIG_TRUE + _CONFIG_FALSE:
vlan.update({'reorder_hdr': opts['reorder_hdr']})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'reorder_hdr', valid)
if 'vlan_id' in opts:
if opts['vlan_id'] > 0:
vlan.update({'vlan_id': opts['vlan_id']})
else:
_raise_error_iface(iface, 'vlan_id', 'Positive integer')
if 'phys_dev' in opts:
if opts['phys_dev']:
vlan.update({'phys_dev': opts['phys_dev']})
else:
_raise_error_iface(iface, 'phys_dev', 'Non-empty string')
return vlan | python | def _parse_settings_vlan(opts, iface):
'''
Filters given options and outputs valid settings for a vlan
'''
vlan = {}
if 'reorder_hdr' in opts:
if opts['reorder_hdr'] in _CONFIG_TRUE + _CONFIG_FALSE:
vlan.update({'reorder_hdr': opts['reorder_hdr']})
else:
valid = _CONFIG_TRUE + _CONFIG_FALSE
_raise_error_iface(iface, 'reorder_hdr', valid)
if 'vlan_id' in opts:
if opts['vlan_id'] > 0:
vlan.update({'vlan_id': opts['vlan_id']})
else:
_raise_error_iface(iface, 'vlan_id', 'Positive integer')
if 'phys_dev' in opts:
if opts['phys_dev']:
vlan.update({'phys_dev': opts['phys_dev']})
else:
_raise_error_iface(iface, 'phys_dev', 'Non-empty string')
return vlan | [
"def",
"_parse_settings_vlan",
"(",
"opts",
",",
"iface",
")",
":",
"vlan",
"=",
"{",
"}",
"if",
"'reorder_hdr'",
"in",
"opts",
":",
"if",
"opts",
"[",
"'reorder_hdr'",
"]",
"in",
"_CONFIG_TRUE",
"+",
"_CONFIG_FALSE",
":",
"vlan",
".",
"update",
"(",
"{"... | Filters given options and outputs valid settings for a vlan | [
"Filters",
"given",
"options",
"and",
"outputs",
"valid",
"settings",
"for",
"a",
"vlan"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L571-L596 | train |
saltstack/salt | salt/modules/rh_ip.py | _parse_settings_eth | def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
result = {'name': iface}
if 'proto' in opts:
valid = ['none', 'bootp', 'dhcp']
if opts['proto'] in valid:
result['proto'] = opts['proto']
else:
_raise_error_iface(iface, opts['proto'], valid)
if 'dns' in opts:
result['dns'] = opts['dns']
result['peerdns'] = 'yes'
if 'mtu' in opts:
try:
result['mtu'] = int(opts['mtu'])
except ValueError:
_raise_error_iface(iface, 'mtu', ['integer'])
if iface_type not in ['bridge']:
ethtool = _parse_ethtool_opts(opts, iface)
if ethtool:
result['ethtool'] = ethtool
if iface_type == 'slave':
result['proto'] = 'none'
if iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
result['bonding'] = bonding
result['devtype'] = "Bond"
if iface_type == 'vlan':
vlan = _parse_settings_vlan(opts, iface)
if vlan:
result['devtype'] = "Vlan"
for opt in vlan:
result[opt] = opts[opt]
if iface_type not in ['bond', 'vlan', 'bridge', 'ipip']:
auto_addr = False
if 'addr' in opts:
if salt.utils.validate.net.mac(opts['addr']):
result['addr'] = opts['addr']
elif opts['addr'] == 'auto':
auto_addr = True
elif opts['addr'] != 'none':
_raise_error_iface(iface, opts['addr'], ['AA:BB:CC:DD:EE:FF', 'auto', 'none'])
else:
auto_addr = True
if auto_addr:
# If interface type is slave for bond, not setting hwaddr
if iface_type != 'slave':
ifaces = __salt__['network.interfaces']()
if iface in ifaces and 'hwaddr' in ifaces[iface]:
result['addr'] = ifaces[iface]['hwaddr']
if iface_type == 'eth':
result['devtype'] = 'Ethernet'
if iface_type == 'bridge':
result['devtype'] = 'Bridge'
bypassfirewall = True
valid = _CONFIG_TRUE + _CONFIG_FALSE
for opt in ['bypassfirewall']:
if opt in opts:
if opts[opt] in _CONFIG_TRUE:
bypassfirewall = True
elif opts[opt] in _CONFIG_FALSE:
bypassfirewall = False
else:
_raise_error_iface(iface, opts[opt], valid)
bridgectls = [
'net.bridge.bridge-nf-call-ip6tables',
'net.bridge.bridge-nf-call-iptables',
'net.bridge.bridge-nf-call-arptables',
]
if bypassfirewall:
sysctl_value = 0
else:
sysctl_value = 1
for sysctl in bridgectls:
try:
__salt__['sysctl.persist'](sysctl, sysctl_value)
except CommandExecutionError:
log.warning('Failed to set sysctl: %s', sysctl)
else:
if 'bridge' in opts:
result['bridge'] = opts['bridge']
if iface_type == 'ipip':
result['devtype'] = 'IPIP'
for opt in ['my_inner_ipaddr', 'my_outer_ipaddr']:
if opt not in opts:
_raise_error_iface(iface, opts[opt], ['1.2.3.4'])
else:
result[opt] = opts[opt]
if iface_type == 'ib':
result['devtype'] = 'InfiniBand'
if 'prefix' in opts:
if 'netmask' in opts:
msg = 'Cannot use prefix and netmask together'
log.error(msg)
raise AttributeError(msg)
result['prefix'] = opts['prefix']
elif 'netmask' in opts:
result['netmask'] = opts['netmask']
for opt in ['ipaddr', 'master', 'srcaddr', 'delay', 'domain', 'gateway', 'uuid', 'nickname', 'zone']:
if opt in opts:
result[opt] = opts[opt]
for opt in ['ipv6addr', 'ipv6gateway']:
if opt in opts:
result[opt] = opts[opt]
if 'ipaddrs' in opts:
result['ipaddrs'] = []
for opt in opts['ipaddrs']:
if salt.utils.validate.net.ipv4_addr(opt):
ip, prefix = [i.strip() for i in opt.split('/')]
result['ipaddrs'].append({'ipaddr': ip, 'prefix': prefix})
else:
msg = 'ipv4 CIDR is invalid'
log.error(msg)
raise AttributeError(msg)
if 'ipv6addrs' in opts:
for opt in opts['ipv6addrs']:
if not salt.utils.validate.net.ipv6_addr(opt):
msg = 'ipv6 CIDR is invalid'
log.error(msg)
raise AttributeError(msg)
result['ipv6addrs'] = opts['ipv6addrs']
if 'enable_ipv6' in opts:
result['enable_ipv6'] = opts['enable_ipv6']
valid = _CONFIG_TRUE + _CONFIG_FALSE
for opt in ['onparent', 'peerdns', 'peerroutes', 'slave', 'vlan', 'defroute', 'stp', 'ipv6_peerdns',
'ipv6_defroute', 'ipv6_peerroutes', 'ipv6_autoconf', 'ipv4_failure_fatal', 'dhcpv6c']:
if opt in opts:
if opts[opt] in _CONFIG_TRUE:
result[opt] = 'yes'
elif opts[opt] in _CONFIG_FALSE:
result[opt] = 'no'
else:
_raise_error_iface(iface, opts[opt], valid)
if 'onboot' in opts:
log.warning(
'The \'onboot\' option is controlled by the \'enabled\' option. '
'Interface: %s Enabled: %s', iface, enabled
)
if enabled:
result['onboot'] = 'yes'
else:
result['onboot'] = 'no'
# If the interface is defined then we want to always take
# control away from non-root users; unless the administrator
# wants to allow non-root users to control the device.
if 'userctl' in opts:
if opts['userctl'] in _CONFIG_TRUE:
result['userctl'] = 'yes'
elif opts['userctl'] in _CONFIG_FALSE:
result['userctl'] = 'no'
else:
_raise_error_iface(iface, opts['userctl'], valid)
else:
result['userctl'] = 'no'
# This vlan is in opts, and should be only used in range interface
# will affect jinja template for interface generating
if 'vlan' in opts:
if opts['vlan'] in _CONFIG_TRUE:
result['vlan'] = 'yes'
elif opts['vlan'] in _CONFIG_FALSE:
result['vlan'] = 'no'
else:
_raise_error_iface(iface, opts['vlan'], valid)
if 'arpcheck' in opts:
if opts['arpcheck'] in _CONFIG_FALSE:
result['arpcheck'] = 'no'
if 'ipaddr_start' in opts:
result['ipaddr_start'] = opts['ipaddr_start']
if 'ipaddr_end' in opts:
result['ipaddr_end'] = opts['ipaddr_end']
if 'clonenum_start' in opts:
result['clonenum_start'] = opts['clonenum_start']
# If NetworkManager is available, we can control whether we use
# it or not
if 'nm_controlled' in opts:
if opts['nm_controlled'] in _CONFIG_TRUE:
result['nm_controlled'] = 'yes'
elif opts['nm_controlled'] in _CONFIG_FALSE:
result['nm_controlled'] = 'no'
else:
_raise_error_iface(iface, opts['nm_controlled'], valid)
else:
result['nm_controlled'] = 'no'
return result | python | def _parse_settings_eth(opts, iface_type, enabled, iface):
'''
Filters given options and outputs valid settings for a
network interface.
'''
result = {'name': iface}
if 'proto' in opts:
valid = ['none', 'bootp', 'dhcp']
if opts['proto'] in valid:
result['proto'] = opts['proto']
else:
_raise_error_iface(iface, opts['proto'], valid)
if 'dns' in opts:
result['dns'] = opts['dns']
result['peerdns'] = 'yes'
if 'mtu' in opts:
try:
result['mtu'] = int(opts['mtu'])
except ValueError:
_raise_error_iface(iface, 'mtu', ['integer'])
if iface_type not in ['bridge']:
ethtool = _parse_ethtool_opts(opts, iface)
if ethtool:
result['ethtool'] = ethtool
if iface_type == 'slave':
result['proto'] = 'none'
if iface_type == 'bond':
bonding = _parse_settings_bond(opts, iface)
if bonding:
result['bonding'] = bonding
result['devtype'] = "Bond"
if iface_type == 'vlan':
vlan = _parse_settings_vlan(opts, iface)
if vlan:
result['devtype'] = "Vlan"
for opt in vlan:
result[opt] = opts[opt]
if iface_type not in ['bond', 'vlan', 'bridge', 'ipip']:
auto_addr = False
if 'addr' in opts:
if salt.utils.validate.net.mac(opts['addr']):
result['addr'] = opts['addr']
elif opts['addr'] == 'auto':
auto_addr = True
elif opts['addr'] != 'none':
_raise_error_iface(iface, opts['addr'], ['AA:BB:CC:DD:EE:FF', 'auto', 'none'])
else:
auto_addr = True
if auto_addr:
# If interface type is slave for bond, not setting hwaddr
if iface_type != 'slave':
ifaces = __salt__['network.interfaces']()
if iface in ifaces and 'hwaddr' in ifaces[iface]:
result['addr'] = ifaces[iface]['hwaddr']
if iface_type == 'eth':
result['devtype'] = 'Ethernet'
if iface_type == 'bridge':
result['devtype'] = 'Bridge'
bypassfirewall = True
valid = _CONFIG_TRUE + _CONFIG_FALSE
for opt in ['bypassfirewall']:
if opt in opts:
if opts[opt] in _CONFIG_TRUE:
bypassfirewall = True
elif opts[opt] in _CONFIG_FALSE:
bypassfirewall = False
else:
_raise_error_iface(iface, opts[opt], valid)
bridgectls = [
'net.bridge.bridge-nf-call-ip6tables',
'net.bridge.bridge-nf-call-iptables',
'net.bridge.bridge-nf-call-arptables',
]
if bypassfirewall:
sysctl_value = 0
else:
sysctl_value = 1
for sysctl in bridgectls:
try:
__salt__['sysctl.persist'](sysctl, sysctl_value)
except CommandExecutionError:
log.warning('Failed to set sysctl: %s', sysctl)
else:
if 'bridge' in opts:
result['bridge'] = opts['bridge']
if iface_type == 'ipip':
result['devtype'] = 'IPIP'
for opt in ['my_inner_ipaddr', 'my_outer_ipaddr']:
if opt not in opts:
_raise_error_iface(iface, opts[opt], ['1.2.3.4'])
else:
result[opt] = opts[opt]
if iface_type == 'ib':
result['devtype'] = 'InfiniBand'
if 'prefix' in opts:
if 'netmask' in opts:
msg = 'Cannot use prefix and netmask together'
log.error(msg)
raise AttributeError(msg)
result['prefix'] = opts['prefix']
elif 'netmask' in opts:
result['netmask'] = opts['netmask']
for opt in ['ipaddr', 'master', 'srcaddr', 'delay', 'domain', 'gateway', 'uuid', 'nickname', 'zone']:
if opt in opts:
result[opt] = opts[opt]
for opt in ['ipv6addr', 'ipv6gateway']:
if opt in opts:
result[opt] = opts[opt]
if 'ipaddrs' in opts:
result['ipaddrs'] = []
for opt in opts['ipaddrs']:
if salt.utils.validate.net.ipv4_addr(opt):
ip, prefix = [i.strip() for i in opt.split('/')]
result['ipaddrs'].append({'ipaddr': ip, 'prefix': prefix})
else:
msg = 'ipv4 CIDR is invalid'
log.error(msg)
raise AttributeError(msg)
if 'ipv6addrs' in opts:
for opt in opts['ipv6addrs']:
if not salt.utils.validate.net.ipv6_addr(opt):
msg = 'ipv6 CIDR is invalid'
log.error(msg)
raise AttributeError(msg)
result['ipv6addrs'] = opts['ipv6addrs']
if 'enable_ipv6' in opts:
result['enable_ipv6'] = opts['enable_ipv6']
valid = _CONFIG_TRUE + _CONFIG_FALSE
for opt in ['onparent', 'peerdns', 'peerroutes', 'slave', 'vlan', 'defroute', 'stp', 'ipv6_peerdns',
'ipv6_defroute', 'ipv6_peerroutes', 'ipv6_autoconf', 'ipv4_failure_fatal', 'dhcpv6c']:
if opt in opts:
if opts[opt] in _CONFIG_TRUE:
result[opt] = 'yes'
elif opts[opt] in _CONFIG_FALSE:
result[opt] = 'no'
else:
_raise_error_iface(iface, opts[opt], valid)
if 'onboot' in opts:
log.warning(
'The \'onboot\' option is controlled by the \'enabled\' option. '
'Interface: %s Enabled: %s', iface, enabled
)
if enabled:
result['onboot'] = 'yes'
else:
result['onboot'] = 'no'
# If the interface is defined then we want to always take
# control away from non-root users; unless the administrator
# wants to allow non-root users to control the device.
if 'userctl' in opts:
if opts['userctl'] in _CONFIG_TRUE:
result['userctl'] = 'yes'
elif opts['userctl'] in _CONFIG_FALSE:
result['userctl'] = 'no'
else:
_raise_error_iface(iface, opts['userctl'], valid)
else:
result['userctl'] = 'no'
# This vlan is in opts, and should be only used in range interface
# will affect jinja template for interface generating
if 'vlan' in opts:
if opts['vlan'] in _CONFIG_TRUE:
result['vlan'] = 'yes'
elif opts['vlan'] in _CONFIG_FALSE:
result['vlan'] = 'no'
else:
_raise_error_iface(iface, opts['vlan'], valid)
if 'arpcheck' in opts:
if opts['arpcheck'] in _CONFIG_FALSE:
result['arpcheck'] = 'no'
if 'ipaddr_start' in opts:
result['ipaddr_start'] = opts['ipaddr_start']
if 'ipaddr_end' in opts:
result['ipaddr_end'] = opts['ipaddr_end']
if 'clonenum_start' in opts:
result['clonenum_start'] = opts['clonenum_start']
# If NetworkManager is available, we can control whether we use
# it or not
if 'nm_controlled' in opts:
if opts['nm_controlled'] in _CONFIG_TRUE:
result['nm_controlled'] = 'yes'
elif opts['nm_controlled'] in _CONFIG_FALSE:
result['nm_controlled'] = 'no'
else:
_raise_error_iface(iface, opts['nm_controlled'], valid)
else:
result['nm_controlled'] = 'no'
return result | [
"def",
"_parse_settings_eth",
"(",
"opts",
",",
"iface_type",
",",
"enabled",
",",
"iface",
")",
":",
"result",
"=",
"{",
"'name'",
":",
"iface",
"}",
"if",
"'proto'",
"in",
"opts",
":",
"valid",
"=",
"[",
"'none'",
",",
"'bootp'",
",",
"'dhcp'",
"]",
... | Filters given options and outputs valid settings for a
network interface. | [
"Filters",
"given",
"options",
"and",
"outputs",
"valid",
"settings",
"for",
"a",
"network",
"interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L599-L816 | train |
saltstack/salt | salt/modules/rh_ip.py | _parse_network_settings | def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
# Check for supported parameters
retain_settings = opts.get('retain_settings', False)
result = current if retain_settings else {}
# Default quote type is an empty string, which will not quote values
quote_type = ''
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
# If networking option is quoted, use its quote type
quote_type = salt.utils.stringutils.is_quoted(opts['networking'])
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
true_val = '{0}yes{0}'.format(quote_type)
false_val = '{0}no{0}'.format(quote_type)
networking = salt.utils.stringutils.dequote(opts['networking'])
if networking in valid:
if networking in _CONFIG_TRUE:
result['networking'] = true_val
elif networking in _CONFIG_FALSE:
result['networking'] = false_val
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except Exception:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = '{1}{0}{1}'.format(
salt.utils.stringutils.dequote(opts['hostname']), quote_type)
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'nozeroconf' in opts:
nozeroconf = salt.utils.stringutils.dequote(opts['nozeroconf'])
if nozeroconf in valid:
if nozeroconf in _CONFIG_TRUE:
result['nozeroconf'] = true_val
elif nozeroconf in _CONFIG_FALSE:
result['nozeroconf'] = false_val
else:
_raise_error_network('nozeroconf', valid)
for opt in opts:
if opt not in ['networking', 'hostname', 'nozeroconf']:
result[opt] = '{1}{0}{1}'.format(
salt.utils.stringutils.dequote(opts[opt]), quote_type)
return result | python | def _parse_network_settings(opts, current):
'''
Filters given options and outputs valid settings for
the global network settings file.
'''
# Normalize keys
opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts))
current = dict((k.lower(), v) for (k, v) in six.iteritems(current))
# Check for supported parameters
retain_settings = opts.get('retain_settings', False)
result = current if retain_settings else {}
# Default quote type is an empty string, which will not quote values
quote_type = ''
valid = _CONFIG_TRUE + _CONFIG_FALSE
if 'enabled' not in opts:
try:
opts['networking'] = current['networking']
# If networking option is quoted, use its quote type
quote_type = salt.utils.stringutils.is_quoted(opts['networking'])
_log_default_network('networking', current['networking'])
except ValueError:
_raise_error_network('networking', valid)
else:
opts['networking'] = opts['enabled']
true_val = '{0}yes{0}'.format(quote_type)
false_val = '{0}no{0}'.format(quote_type)
networking = salt.utils.stringutils.dequote(opts['networking'])
if networking in valid:
if networking in _CONFIG_TRUE:
result['networking'] = true_val
elif networking in _CONFIG_FALSE:
result['networking'] = false_val
else:
_raise_error_network('networking', valid)
if 'hostname' not in opts:
try:
opts['hostname'] = current['hostname']
_log_default_network('hostname', current['hostname'])
except Exception:
_raise_error_network('hostname', ['server1.example.com'])
if opts['hostname']:
result['hostname'] = '{1}{0}{1}'.format(
salt.utils.stringutils.dequote(opts['hostname']), quote_type)
else:
_raise_error_network('hostname', ['server1.example.com'])
if 'nozeroconf' in opts:
nozeroconf = salt.utils.stringutils.dequote(opts['nozeroconf'])
if nozeroconf in valid:
if nozeroconf in _CONFIG_TRUE:
result['nozeroconf'] = true_val
elif nozeroconf in _CONFIG_FALSE:
result['nozeroconf'] = false_val
else:
_raise_error_network('nozeroconf', valid)
for opt in opts:
if opt not in ['networking', 'hostname', 'nozeroconf']:
result[opt] = '{1}{0}{1}'.format(
salt.utils.stringutils.dequote(opts[opt]), quote_type)
return result | [
"def",
"_parse_network_settings",
"(",
"opts",
",",
"current",
")",
":",
"# Normalize keys",
"opts",
"=",
"dict",
"(",
"(",
"k",
".",
"lower",
"(",
")",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"opts",
")",... | Filters given options and outputs valid settings for
the global network settings file. | [
"Filters",
"given",
"options",
"and",
"outputs",
"valid",
"settings",
"for",
"the",
"global",
"network",
"settings",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L836-L903 | train |
saltstack/salt | salt/modules/rh_ip.py | _read_file | def _read_file(path):
'''
Reads and returns the contents of a file
'''
try:
with salt.utils.files.fopen(path, 'rb') as rfh:
lines = salt.utils.stringutils.to_unicode(rfh.read()).splitlines()
try:
lines.remove('')
except ValueError:
pass
return lines
except Exception:
return [] | python | def _read_file(path):
'''
Reads and returns the contents of a file
'''
try:
with salt.utils.files.fopen(path, 'rb') as rfh:
lines = salt.utils.stringutils.to_unicode(rfh.read()).splitlines()
try:
lines.remove('')
except ValueError:
pass
return lines
except Exception:
return [] | [
"def",
"_read_file",
"(",
"path",
")",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"'rb'",
")",
"as",
"rfh",
":",
"lines",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"rfh"... | Reads and returns the contents of a file | [
"Reads",
"and",
"returns",
"the",
"contents",
"of",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L933-L946 | train |
saltstack/salt | salt/modules/rh_ip.py | _write_file_iface | def _write_file_iface(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(data)) | python | def _write_file_iface(iface, data, folder, pattern):
'''
Writes a file to disk
'''
filename = os.path.join(folder, pattern.format(iface))
if not os.path.exists(folder):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.files.fopen(filename, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(data)) | [
"def",
"_write_file_iface",
"(",
"iface",
",",
"data",
",",
"folder",
",",
"pattern",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"pattern",
".",
"format",
"(",
"iface",
")",
")",
"if",
"not",
"os",
".",
"path",
"... | Writes a file to disk | [
"Writes",
"a",
"file",
"to",
"disk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L949-L960 | train |
saltstack/salt | salt/modules/rh_ip.py | _write_file_network | def _write_file_network(data, filename):
'''
Writes a file to disk
'''
with salt.utils.files.fopen(filename, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(data)) | python | def _write_file_network(data, filename):
'''
Writes a file to disk
'''
with salt.utils.files.fopen(filename, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(data)) | [
"def",
"_write_file_network",
"(",
"data",
",",
"filename",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp_",
":",
"fp_",
".",
"write",
"(",
"salt",
".",
"utils",
".",
"stringutils",
".... | Writes a file to disk | [
"Writes",
"a",
"file",
"to",
"disk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L963-L968 | train |
saltstack/salt | salt/modules/rh_ip.py | build_bond | def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
rh_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
_write_file_iface(iface, data, _RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if rh_major == '5':
__salt__['cmd.run'](
'sed -i -e "/^alias\\s{0}.*/d" /etc/modprobe.conf'.format(iface),
python_shell=False
)
__salt__['cmd.run'](
'sed -i -e "/^options\\s{0}.*/d" /etc/modprobe.conf'.format(iface),
python_shell=False
)
__salt__['file.append']('/etc/modprobe.conf', path)
__salt__['kmod.load']('bonding')
if settings['test']:
return _read_temp(data)
return _read_file(path) | python | def build_bond(iface, **settings):
'''
Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb
'''
rh_major = __grains__['osrelease'][:1]
opts = _parse_settings_bond(settings, iface)
try:
template = JINJA.get_template('conf.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template conf.jinja')
return ''
data = template.render({'name': iface, 'bonding': opts})
_write_file_iface(iface, data, _RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
if rh_major == '5':
__salt__['cmd.run'](
'sed -i -e "/^alias\\s{0}.*/d" /etc/modprobe.conf'.format(iface),
python_shell=False
)
__salt__['cmd.run'](
'sed -i -e "/^options\\s{0}.*/d" /etc/modprobe.conf'.format(iface),
python_shell=False
)
__salt__['file.append']('/etc/modprobe.conf', path)
__salt__['kmod.load']('bonding')
if settings['test']:
return _read_temp(data)
return _read_file(path) | [
"def",
"build_bond",
"(",
"iface",
",",
"*",
"*",
"settings",
")",
":",
"rh_major",
"=",
"__grains__",
"[",
"'osrelease'",
"]",
"[",
":",
"1",
"]",
"opts",
"=",
"_parse_settings_bond",
"(",
"settings",
",",
"iface",
")",
"try",
":",
"template",
"=",
"J... | Create a bond script in /etc/modprobe.d with the passed settings
and load the bonding kernel module.
CLI Example:
.. code-block:: bash
salt '*' ip.build_bond bond0 mode=balance-alb | [
"Create",
"a",
"bond",
"script",
"in",
"/",
"etc",
"/",
"modprobe",
".",
"d",
"with",
"the",
"passed",
"settings",
"and",
"load",
"the",
"bonding",
"kernel",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L980-L1017 | train |
saltstack/salt | salt/modules/rh_ip.py | build_interface | def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
if __grains__['os'] == 'Fedora':
if __grains__['osmajorrelease'] >= 18:
rh_major = '7'
else:
rh_major = '6'
else:
rh_major = __grains__['osrelease'][:1]
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
if iface_type == 'vlan':
settings['vlan'] = 'yes'
if iface_type == 'bridge':
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'ipip', 'ib', 'alias']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
try:
template = JINJA.get_template('rh{0}_eth.jinja'.format(rh_major))
except jinja2.exceptions.TemplateNotFound:
log.error(
'Could not load template rh%s_eth.jinja',
rh_major
)
return ''
ifcfg = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(ifcfg)
_write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}')
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface))
return _read_file(path) | python | def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
if __grains__['os'] == 'Fedora':
if __grains__['osmajorrelease'] >= 18:
rh_major = '7'
else:
rh_major = '6'
else:
rh_major = __grains__['osrelease'][:1]
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
if iface_type == 'vlan':
settings['vlan'] = 'yes'
if iface_type == 'bridge':
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'ipip', 'ib', 'alias']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
try:
template = JINJA.get_template('rh{0}_eth.jinja'.format(rh_major))
except jinja2.exceptions.TemplateNotFound:
log.error(
'Could not load template rh%s_eth.jinja',
rh_major
)
return ''
ifcfg = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(ifcfg)
_write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}')
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface))
return _read_file(path) | [
"def",
"build_interface",
"(",
"iface",
",",
"iface_type",
",",
"enabled",
",",
"*",
"*",
"settings",
")",
":",
"if",
"__grains__",
"[",
"'os'",
"]",
"==",
"'Fedora'",
":",
"if",
"__grains__",
"[",
"'osmajorrelease'",
"]",
">=",
"18",
":",
"rh_major",
"=... | Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings> | [
"Build",
"an",
"interface",
"script",
"for",
"a",
"network",
"interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L1020-L1074 | train |
saltstack/salt | salt/modules/rh_ip.py | build_routes | def build_routes(iface, **settings):
'''
Build a route script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
template = 'rh6_route_eth.jinja'
try:
if int(__grains__['osrelease'][0]) < 6:
template = 'route_eth.jinja'
except ValueError:
pass
log.debug('Template name: %s', template)
opts = _parse_routes(iface, settings)
log.debug('Opts: \n %s', opts)
try:
template = JINJA.get_template(template)
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template %s', template)
return ''
opts6 = []
opts4 = []
for route in opts['routes']:
ipaddr = route['ipaddr']
if salt.utils.validate.net.ipv6_addr(ipaddr):
opts6.append(route)
else:
opts4.append(route)
log.debug("IPv4 routes:\n%s", opts4)
log.debug("IPv6 routes:\n%s", opts6)
routecfg = template.render(routes=opts4, iface=iface)
routecfg6 = template.render(routes=opts6, iface=iface)
if settings['test']:
routes = _read_temp(routecfg)
routes.extend(_read_temp(routecfg6))
return routes
_write_file_iface(iface, routecfg, _RH_NETWORK_SCRIPT_DIR, 'route-{0}')
_write_file_iface(iface, routecfg6, _RH_NETWORK_SCRIPT_DIR, 'route6-{0}')
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface))
path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface))
routes = _read_file(path)
routes.extend(_read_file(path6))
return routes | python | def build_routes(iface, **settings):
'''
Build a route script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
template = 'rh6_route_eth.jinja'
try:
if int(__grains__['osrelease'][0]) < 6:
template = 'route_eth.jinja'
except ValueError:
pass
log.debug('Template name: %s', template)
opts = _parse_routes(iface, settings)
log.debug('Opts: \n %s', opts)
try:
template = JINJA.get_template(template)
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template %s', template)
return ''
opts6 = []
opts4 = []
for route in opts['routes']:
ipaddr = route['ipaddr']
if salt.utils.validate.net.ipv6_addr(ipaddr):
opts6.append(route)
else:
opts4.append(route)
log.debug("IPv4 routes:\n%s", opts4)
log.debug("IPv6 routes:\n%s", opts6)
routecfg = template.render(routes=opts4, iface=iface)
routecfg6 = template.render(routes=opts6, iface=iface)
if settings['test']:
routes = _read_temp(routecfg)
routes.extend(_read_temp(routecfg6))
return routes
_write_file_iface(iface, routecfg, _RH_NETWORK_SCRIPT_DIR, 'route-{0}')
_write_file_iface(iface, routecfg6, _RH_NETWORK_SCRIPT_DIR, 'route6-{0}')
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface))
path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface))
routes = _read_file(path)
routes.extend(_read_file(path6))
return routes | [
"def",
"build_routes",
"(",
"iface",
",",
"*",
"*",
"settings",
")",
":",
"template",
"=",
"'rh6_route_eth.jinja'",
"try",
":",
"if",
"int",
"(",
"__grains__",
"[",
"'osrelease'",
"]",
"[",
"0",
"]",
")",
"<",
"6",
":",
"template",
"=",
"'route_eth.jinja... | Build a route script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings> | [
"Build",
"a",
"route",
"script",
"for",
"a",
"network",
"interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L1077-L1130 | train |
saltstack/salt | salt/modules/rh_ip.py | get_bond | def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path) | python | def get_bond(iface):
'''
Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0
'''
path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
return _read_file(path) | [
"def",
"get_bond",
"(",
"iface",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_RH_NETWORK_CONF_FILES",
",",
"'{0}.conf'",
".",
"format",
"(",
"iface",
")",
")",
"return",
"_read_file",
"(",
"path",
")"
] | Return the content of a bond script
CLI Example:
.. code-block:: bash
salt '*' ip.get_bond bond0 | [
"Return",
"the",
"content",
"of",
"a",
"bond",
"script"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L1149-L1160 | train |
saltstack/salt | salt/modules/rh_ip.py | get_interface | def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface))
return _read_file(path) | python | def get_interface(iface):
'''
Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface))
return _read_file(path) | [
"def",
"get_interface",
"(",
"iface",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_RH_NETWORK_SCRIPT_DIR",
",",
"'ifcfg-{0}'",
".",
"format",
"(",
"iface",
")",
")",
"return",
"_read_file",
"(",
"path",
")"
] | Return the contents of an interface script
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0 | [
"Return",
"the",
"contents",
"of",
"an",
"interface",
"script"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L1163-L1174 | train |
saltstack/salt | salt/modules/rh_ip.py | get_routes | def get_routes(iface):
'''
Return the contents of the interface routes script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface))
path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface))
routes = _read_file(path)
routes.extend(_read_file(path6))
return routes | python | def get_routes(iface):
'''
Return the contents of the interface routes script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0
'''
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface))
path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface))
routes = _read_file(path)
routes.extend(_read_file(path6))
return routes | [
"def",
"get_routes",
"(",
"iface",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_RH_NETWORK_SCRIPT_DIR",
",",
"'route-{0}'",
".",
"format",
"(",
"iface",
")",
")",
"path6",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_RH_NETWORK_SCRIPT_DIR... | Return the contents of the interface routes script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_routes eth0 | [
"Return",
"the",
"contents",
"of",
"the",
"interface",
"routes",
"script",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L1193-L1207 | train |
saltstack/salt | salt/modules/rh_ip.py | apply_network_settings | def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
res = __salt__['service.restart']('network')
return hostname_res and res | python | def apply_network_settings(**settings):
'''
Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings
'''
if 'require_reboot' not in settings:
settings['require_reboot'] = False
if 'apply_hostname' not in settings:
settings['apply_hostname'] = False
hostname_res = True
if settings['apply_hostname'] in _CONFIG_TRUE:
if 'hostname' in settings:
hostname_res = __salt__['network.mod_hostname'](settings['hostname'])
else:
log.warning(
'The network state sls is trying to apply hostname '
'changes but no hostname is defined.'
)
hostname_res = False
res = True
if settings['require_reboot'] in _CONFIG_TRUE:
log.warning(
'The network state sls is requiring a reboot of the system to '
'properly apply network configuration.'
)
res = True
else:
res = __salt__['service.restart']('network')
return hostname_res and res | [
"def",
"apply_network_settings",
"(",
"*",
"*",
"settings",
")",
":",
"if",
"'require_reboot'",
"not",
"in",
"settings",
":",
"settings",
"[",
"'require_reboot'",
"]",
"=",
"False",
"if",
"'apply_hostname'",
"not",
"in",
"settings",
":",
"settings",
"[",
"'app... | Apply global network configuration.
CLI Example:
.. code-block:: bash
salt '*' ip.apply_network_settings | [
"Apply",
"global",
"network",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L1223-L1260 | train |
saltstack/salt | salt/modules/rh_ip.py | build_network_settings | def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
# Read current configuration and store default values
current_network_settings = _parse_rh_config(_RH_NETWORK_FILE)
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _RH_NETWORK_FILE)
return _read_file(_RH_NETWORK_FILE) | python | def build_network_settings(**settings):
'''
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
'''
# Read current configuration and store default values
current_network_settings = _parse_rh_config(_RH_NETWORK_FILE)
# Build settings
opts = _parse_network_settings(settings, current_network_settings)
try:
template = JINJA.get_template('network.jinja')
except jinja2.exceptions.TemplateNotFound:
log.error('Could not load template network.jinja')
return ''
network = template.render(opts)
if settings['test']:
return _read_temp(network)
# Write settings
_write_file_network(network, _RH_NETWORK_FILE)
return _read_file(_RH_NETWORK_FILE) | [
"def",
"build_network_settings",
"(",
"*",
"*",
"settings",
")",
":",
"# Read current configuration and store default values",
"current_network_settings",
"=",
"_parse_rh_config",
"(",
"_RH_NETWORK_FILE",
")",
"# Build settings",
"opts",
"=",
"_parse_network_settings",
"(",
"... | Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings> | [
"Build",
"the",
"global",
"network",
"script",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L1263-L1291 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.