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/gnomedesktop.py | setIdleDelay | def setIdleDelay(delaySeconds, **kwargs):
'''
Set the current idle delay setting in seconds
CLI Example:
.. code-block:: bash
salt '*' gnome.setIdleDelay <seconds> user=<username>
'''
_gsession = _GSettings(user=kwargs.get('user'),
schema='org.gnome.desktop.session',
key='idle-delay')
return _gsession._set(delaySeconds) | python | def setIdleDelay(delaySeconds, **kwargs):
'''
Set the current idle delay setting in seconds
CLI Example:
.. code-block:: bash
salt '*' gnome.setIdleDelay <seconds> user=<username>
'''
_gsession = _GSettings(user=kwargs.get('user'),
schema='org.gnome.desktop.session',
key='idle-delay')
return _gsession._set(delaySeconds) | [
"def",
"setIdleDelay",
"(",
"delaySeconds",
",",
"*",
"*",
"kwargs",
")",
":",
"_gsession",
"=",
"_GSettings",
"(",
"user",
"=",
"kwargs",
".",
"get",
"(",
"'user'",
")",
",",
"schema",
"=",
"'org.gnome.desktop.session'",
",",
"key",
"=",
"'idle-delay'",
"... | Set the current idle delay setting in seconds
CLI Example:
.. code-block:: bash
salt '*' gnome.setIdleDelay <seconds> user=<username> | [
"Set",
"the",
"current",
"idle",
"delay",
"setting",
"in",
"seconds"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gnomedesktop.py#L144-L158 | train |
saltstack/salt | salt/modules/gnomedesktop.py | setClockFormat | def setClockFormat(clockFormat, **kwargs):
'''
Set the clock format, either 12h or 24h format.
CLI Example:
.. code-block:: bash
salt '*' gnome.setClockFormat <12h|24h> user=<username>
'''
if clockFormat != '12h' and clockFormat != '24h':
return False
_gsession = _GSettings(user=kwargs.get('user'),
schema='org.gnome.desktop.interface',
key='clock-format')
return _gsession._set(clockFormat) | python | def setClockFormat(clockFormat, **kwargs):
'''
Set the clock format, either 12h or 24h format.
CLI Example:
.. code-block:: bash
salt '*' gnome.setClockFormat <12h|24h> user=<username>
'''
if clockFormat != '12h' and clockFormat != '24h':
return False
_gsession = _GSettings(user=kwargs.get('user'),
schema='org.gnome.desktop.interface',
key='clock-format')
return _gsession._set(clockFormat) | [
"def",
"setClockFormat",
"(",
"clockFormat",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"clockFormat",
"!=",
"'12h'",
"and",
"clockFormat",
"!=",
"'24h'",
":",
"return",
"False",
"_gsession",
"=",
"_GSettings",
"(",
"user",
"=",
"kwargs",
".",
"get",
"(",
... | Set the clock format, either 12h or 24h format.
CLI Example:
.. code-block:: bash
salt '*' gnome.setClockFormat <12h|24h> user=<username> | [
"Set",
"the",
"clock",
"format",
"either",
"12h",
"or",
"24h",
"format",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gnomedesktop.py#L178-L194 | train |
saltstack/salt | salt/modules/gnomedesktop.py | setClockShowDate | def setClockShowDate(kvalue, **kwargs):
'''
Set whether the date is visible in the clock
CLI Example:
.. code-block:: bash
salt '*' gnome.setClockShowDate <True|False> user=<username>
'''
if kvalue is not True and kvalue is not False:
return False
_gsession = _GSettings(user=kwargs.get('user'),
schema='org.gnome.desktop.interface',
key='clock-show-date')
return _gsession._set(kvalue) | python | def setClockShowDate(kvalue, **kwargs):
'''
Set whether the date is visible in the clock
CLI Example:
.. code-block:: bash
salt '*' gnome.setClockShowDate <True|False> user=<username>
'''
if kvalue is not True and kvalue is not False:
return False
_gsession = _GSettings(user=kwargs.get('user'),
schema='org.gnome.desktop.interface',
key='clock-show-date')
return _gsession._set(kvalue) | [
"def",
"setClockShowDate",
"(",
"kvalue",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kvalue",
"is",
"not",
"True",
"and",
"kvalue",
"is",
"not",
"False",
":",
"return",
"False",
"_gsession",
"=",
"_GSettings",
"(",
"user",
"=",
"kwargs",
".",
"get",
"("... | Set whether the date is visible in the clock
CLI Example:
.. code-block:: bash
salt '*' gnome.setClockShowDate <True|False> user=<username> | [
"Set",
"whether",
"the",
"date",
"is",
"visible",
"in",
"the",
"clock"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gnomedesktop.py#L214-L230 | train |
saltstack/salt | salt/modules/gnomedesktop.py | getIdleActivation | def getIdleActivation(**kwargs):
'''
Get whether the idle activation is enabled
CLI Example:
.. code-block:: bash
salt '*' gnome.getIdleActivation user=<username>
'''
_gsession = _GSettings(user=kwargs.get('user'),
schema='org.gnome.desktop.screensaver',
key='idle-activation-enabled')
return _gsession._get() | python | def getIdleActivation(**kwargs):
'''
Get whether the idle activation is enabled
CLI Example:
.. code-block:: bash
salt '*' gnome.getIdleActivation user=<username>
'''
_gsession = _GSettings(user=kwargs.get('user'),
schema='org.gnome.desktop.screensaver',
key='idle-activation-enabled')
return _gsession._get() | [
"def",
"getIdleActivation",
"(",
"*",
"*",
"kwargs",
")",
":",
"_gsession",
"=",
"_GSettings",
"(",
"user",
"=",
"kwargs",
".",
"get",
"(",
"'user'",
")",
",",
"schema",
"=",
"'org.gnome.desktop.screensaver'",
",",
"key",
"=",
"'idle-activation-enabled'",
")",... | Get whether the idle activation is enabled
CLI Example:
.. code-block:: bash
salt '*' gnome.getIdleActivation user=<username> | [
"Get",
"whether",
"the",
"idle",
"activation",
"is",
"enabled"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gnomedesktop.py#L233-L247 | train |
saltstack/salt | salt/modules/gnomedesktop.py | get | def get(schema=None, key=None, user=None, **kwargs):
'''
Get key in a particular GNOME schema
CLI Example:
.. code-block:: bash
salt '*' gnome.get user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled
'''
_gsession = _GSettings(user=user, schema=schema, key=key)
return _gsession._get() | python | def get(schema=None, key=None, user=None, **kwargs):
'''
Get key in a particular GNOME schema
CLI Example:
.. code-block:: bash
salt '*' gnome.get user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled
'''
_gsession = _GSettings(user=user, schema=schema, key=key)
return _gsession._get() | [
"def",
"get",
"(",
"schema",
"=",
"None",
",",
"key",
"=",
"None",
",",
"user",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_gsession",
"=",
"_GSettings",
"(",
"user",
"=",
"user",
",",
"schema",
"=",
"schema",
",",
"key",
"=",
"key",
")",
... | Get key in a particular GNOME schema
CLI Example:
.. code-block:: bash
salt '*' gnome.get user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled | [
"Get",
"key",
"in",
"a",
"particular",
"GNOME",
"schema"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gnomedesktop.py#L269-L281 | train |
saltstack/salt | salt/modules/gnomedesktop.py | set_ | def set_(schema=None, key=None, user=None, value=None, **kwargs):
'''
Set key in a particular GNOME schema
CLI Example:
.. code-block:: bash
salt '*' gnome.set user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled value=False
'''
_gsession = _GSettings(user=user, schema=schema, key=key)
return _gsession._set(value) | python | def set_(schema=None, key=None, user=None, value=None, **kwargs):
'''
Set key in a particular GNOME schema
CLI Example:
.. code-block:: bash
salt '*' gnome.set user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled value=False
'''
_gsession = _GSettings(user=user, schema=schema, key=key)
return _gsession._set(value) | [
"def",
"set_",
"(",
"schema",
"=",
"None",
",",
"key",
"=",
"None",
",",
"user",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_gsession",
"=",
"_GSettings",
"(",
"user",
"=",
"user",
",",
"schema",
"=",
"schema",
",... | Set key in a particular GNOME schema
CLI Example:
.. code-block:: bash
salt '*' gnome.set user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled value=False | [
"Set",
"key",
"in",
"a",
"particular",
"GNOME",
"schema"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gnomedesktop.py#L284-L296 | train |
saltstack/salt | salt/modules/gnomedesktop.py | _GSettings._get | def _get(self):
'''
get the value for user in gsettings
'''
user = self.USER
try:
uid = pwd.getpwnam(user).pw_uid
except KeyError:
log.info('User does not exist')
return False
cmd = self.gsetting_command + ['get', str(self.SCHEMA), str(self.KEY)]
environ = {}
environ['XDG_RUNTIME_DIR'] = '/run/user/{0}'.format(uid)
result = __salt__['cmd.run_all'](cmd, runas=user, env=environ, python_shell=False)
if 'stdout' in result:
if 'uint32' in result['stdout']:
return re.sub('uint32 ', '', result['stdout'])
else:
return result['stdout']
else:
return False | python | def _get(self):
'''
get the value for user in gsettings
'''
user = self.USER
try:
uid = pwd.getpwnam(user).pw_uid
except KeyError:
log.info('User does not exist')
return False
cmd = self.gsetting_command + ['get', str(self.SCHEMA), str(self.KEY)]
environ = {}
environ['XDG_RUNTIME_DIR'] = '/run/user/{0}'.format(uid)
result = __salt__['cmd.run_all'](cmd, runas=user, env=environ, python_shell=False)
if 'stdout' in result:
if 'uint32' in result['stdout']:
return re.sub('uint32 ', '', result['stdout'])
else:
return result['stdout']
else:
return False | [
"def",
"_get",
"(",
"self",
")",
":",
"user",
"=",
"self",
".",
"USER",
"try",
":",
"uid",
"=",
"pwd",
".",
"getpwnam",
"(",
"user",
")",
".",
"pw_uid",
"except",
"KeyError",
":",
"log",
".",
"info",
"(",
"'User does not exist'",
")",
"return",
"Fals... | get the value for user in gsettings | [
"get",
"the",
"value",
"for",
"user",
"in",
"gsettings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gnomedesktop.py#L66-L89 | train |
saltstack/salt | salt/modules/gnomedesktop.py | _GSettings._set | def _set(self, value):
'''
set the value for user in gsettings
'''
user = self.USER
try:
uid = pwd.getpwnam(user).pw_uid
except KeyError:
log.info('User does not exist')
result = {}
result['retcode'] = 1
result['stdout'] = 'User {0} does not exist'.format(user)
return result
cmd = self.gsetting_command + ['set', self.SCHEMA, self.KEY, value]
environ = {}
environ['XDG_RUNTIME_DIR'] = '/run/user/{0}'.format(uid)
result = __salt__['cmd.run_all'](cmd, runas=user, env=environ, python_shell=False)
return result | python | def _set(self, value):
'''
set the value for user in gsettings
'''
user = self.USER
try:
uid = pwd.getpwnam(user).pw_uid
except KeyError:
log.info('User does not exist')
result = {}
result['retcode'] = 1
result['stdout'] = 'User {0} does not exist'.format(user)
return result
cmd = self.gsetting_command + ['set', self.SCHEMA, self.KEY, value]
environ = {}
environ['XDG_RUNTIME_DIR'] = '/run/user/{0}'.format(uid)
result = __salt__['cmd.run_all'](cmd, runas=user, env=environ, python_shell=False)
return result | [
"def",
"_set",
"(",
"self",
",",
"value",
")",
":",
"user",
"=",
"self",
".",
"USER",
"try",
":",
"uid",
"=",
"pwd",
".",
"getpwnam",
"(",
"user",
")",
".",
"pw_uid",
"except",
"KeyError",
":",
"log",
".",
"info",
"(",
"'User does not exist'",
")",
... | set the value for user in gsettings | [
"set",
"the",
"value",
"for",
"user",
"in",
"gsettings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gnomedesktop.py#L91-L110 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | bin_pkg_info | def bin_pkg_info(path, saltenv='base'):
'''
.. versionadded:: 2015.8.0
Parses RPM metadata and returns a dictionary of information about the
package (name, version, etc.).
path
Path to the file. Can either be an absolute path to a file on the
minion, or a salt fileserver URL (e.g. ``salt://path/to/file.rpm``).
If a salt fileserver URL is passed, the file will be cached to the
minion so that it can be examined.
saltenv : base
Salt fileserver environment from which to retrieve the package. Ignored
if ``path`` is a local file path on the minion.
CLI Example:
.. code-block:: bash
salt '*' lowpkg.bin_pkg_info /root/salt-2015.5.1-2.el7.noarch.rpm
salt '*' lowpkg.bin_pkg_info salt://salt-2015.5.1-2.el7.noarch.rpm
'''
# If the path is a valid protocol, pull it down using cp.cache_file
if __salt__['config.valid_fileproto'](path):
newpath = __salt__['cp.cache_file'](path, saltenv)
if not newpath:
raise CommandExecutionError(
'Unable to retrieve {0} from saltenv \'{1}\''
.format(path, saltenv)
)
path = newpath
else:
if not os.path.exists(path):
raise CommandExecutionError(
'{0} does not exist on minion'.format(path)
)
elif not os.path.isabs(path):
raise SaltInvocationError(
'{0} does not exist on minion'.format(path)
)
# REPOID is not a valid tag for the rpm command. Remove it and replace it
# with 'none'
queryformat = salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', 'none')
output = __salt__['cmd.run_stdout'](
['rpm', '-qp', '--queryformat', queryformat, path],
output_loglevel='trace',
ignore_retcode=True,
python_shell=False
)
ret = {}
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
output,
osarch=__grains__['osarch']
)
try:
for field in pkginfo._fields:
ret[field] = getattr(pkginfo, field)
except AttributeError:
# pkginfo is None
return None
return ret | python | def bin_pkg_info(path, saltenv='base'):
'''
.. versionadded:: 2015.8.0
Parses RPM metadata and returns a dictionary of information about the
package (name, version, etc.).
path
Path to the file. Can either be an absolute path to a file on the
minion, or a salt fileserver URL (e.g. ``salt://path/to/file.rpm``).
If a salt fileserver URL is passed, the file will be cached to the
minion so that it can be examined.
saltenv : base
Salt fileserver environment from which to retrieve the package. Ignored
if ``path`` is a local file path on the minion.
CLI Example:
.. code-block:: bash
salt '*' lowpkg.bin_pkg_info /root/salt-2015.5.1-2.el7.noarch.rpm
salt '*' lowpkg.bin_pkg_info salt://salt-2015.5.1-2.el7.noarch.rpm
'''
# If the path is a valid protocol, pull it down using cp.cache_file
if __salt__['config.valid_fileproto'](path):
newpath = __salt__['cp.cache_file'](path, saltenv)
if not newpath:
raise CommandExecutionError(
'Unable to retrieve {0} from saltenv \'{1}\''
.format(path, saltenv)
)
path = newpath
else:
if not os.path.exists(path):
raise CommandExecutionError(
'{0} does not exist on minion'.format(path)
)
elif not os.path.isabs(path):
raise SaltInvocationError(
'{0} does not exist on minion'.format(path)
)
# REPOID is not a valid tag for the rpm command. Remove it and replace it
# with 'none'
queryformat = salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', 'none')
output = __salt__['cmd.run_stdout'](
['rpm', '-qp', '--queryformat', queryformat, path],
output_loglevel='trace',
ignore_retcode=True,
python_shell=False
)
ret = {}
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
output,
osarch=__grains__['osarch']
)
try:
for field in pkginfo._fields:
ret[field] = getattr(pkginfo, field)
except AttributeError:
# pkginfo is None
return None
return ret | [
"def",
"bin_pkg_info",
"(",
"path",
",",
"saltenv",
"=",
"'base'",
")",
":",
"# If the path is a valid protocol, pull it down using cp.cache_file",
"if",
"__salt__",
"[",
"'config.valid_fileproto'",
"]",
"(",
"path",
")",
":",
"newpath",
"=",
"__salt__",
"[",
"'cp.cac... | .. versionadded:: 2015.8.0
Parses RPM metadata and returns a dictionary of information about the
package (name, version, etc.).
path
Path to the file. Can either be an absolute path to a file on the
minion, or a salt fileserver URL (e.g. ``salt://path/to/file.rpm``).
If a salt fileserver URL is passed, the file will be cached to the
minion so that it can be examined.
saltenv : base
Salt fileserver environment from which to retrieve the package. Ignored
if ``path`` is a local file path on the minion.
CLI Example:
.. code-block:: bash
salt '*' lowpkg.bin_pkg_info /root/salt-2015.5.1-2.el7.noarch.rpm
salt '*' lowpkg.bin_pkg_info salt://salt-2015.5.1-2.el7.noarch.rpm | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L65-L128 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | list_pkgs | def list_pkgs(*packages, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
root
use root as top level directory (default: "/")
CLI Example:
.. code-block:: bash
salt '*' lowpkg.list_pkgs
'''
pkgs = {}
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-q' if packages else '-qa',
'--queryformat', r'%{NAME} %{VERSION}\n'])
if packages:
cmd.extend(packages)
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if 'is not installed' in line:
continue
comps = line.split()
pkgs[comps[0]] = comps[1]
return pkgs | python | def list_pkgs(*packages, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
root
use root as top level directory (default: "/")
CLI Example:
.. code-block:: bash
salt '*' lowpkg.list_pkgs
'''
pkgs = {}
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-q' if packages else '-qa',
'--queryformat', r'%{NAME} %{VERSION}\n'])
if packages:
cmd.extend(packages)
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if 'is not installed' in line:
continue
comps = line.split()
pkgs[comps[0]] = comps[1]
return pkgs | [
"def",
"list_pkgs",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"pkgs",
"=",
"{",
"}",
"cmd",
"=",
"[",
"'rpm'",
"]",
"if",
"kwargs",
".",
"get",
"(",
"'root'",
")",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--root'",
",",
"kwargs",
"... | List the packages currently installed in a dict::
{'<package_name>': '<version>'}
root
use root as top level directory (default: "/")
CLI Example:
.. code-block:: bash
salt '*' lowpkg.list_pkgs | [
"List",
"the",
"packages",
"currently",
"installed",
"in",
"a",
"dict",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L131-L160 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | verify | def verify(*packages, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
root
use root as top level directory (default: "/")
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument
CLI Example:
.. code-block:: bash
salt '*' lowpkg.verify
salt '*' lowpkg.verify httpd
salt '*' lowpkg.verify httpd postfix
salt '*' lowpkg.verify httpd postfix ignore_types=['config','doc']
'''
ftypes = {'c': 'config',
'd': 'doc',
'g': 'ghost',
'l': 'license',
'r': 'readme'}
ret = {}
ignore_types = kwargs.get('ignore_types', [])
if not isinstance(ignore_types, (list, six.string_types)):
raise SaltInvocationError(
'ignore_types must be a list or a comma-separated string'
)
if isinstance(ignore_types, six.string_types):
try:
ignore_types = [x.strip() for x in ignore_types.split(',')]
except AttributeError:
ignore_types = [x.strip() for x in six.text_type(ignore_types).split(',')]
verify_options = kwargs.get('verify_options', [])
if not isinstance(verify_options, (list, six.string_types)):
raise SaltInvocationError(
'verify_options must be a list or a comma-separated string'
)
if isinstance(verify_options, six.string_types):
try:
verify_options = [x.strip() for x in verify_options.split(',')]
except AttributeError:
verify_options = [x.strip() for x in six.text_type(verify_options).split(',')]
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['--' + x for x in verify_options])
if packages:
cmd.append('-V')
# Can't concatenate a tuple, must do a list.extend()
cmd.extend(packages)
else:
cmd.append('-Va')
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if not out['stdout'].strip() and out['retcode'] != 0:
# If there is no stdout and the retcode is 0, then verification
# succeeded, but if the retcode is nonzero, then the command failed.
msg = 'Failed to verify package(s)'
if out['stderr']:
msg += ': {0}'.format(out['stderr'])
raise CommandExecutionError(msg)
for line in salt.utils.itertools.split(out['stdout'], '\n'):
fdict = {'mismatch': []}
if 'missing' in line:
line = ' ' + line
fdict['missing'] = True
del fdict['mismatch']
fname = line[13:]
if line[11:12] in ftypes:
fdict['type'] = ftypes[line[11:12]]
if 'type' not in fdict or fdict['type'] not in ignore_types:
if line[0:1] == 'S':
fdict['mismatch'].append('size')
if line[1:2] == 'M':
fdict['mismatch'].append('mode')
if line[2:3] == '5':
fdict['mismatch'].append('md5sum')
if line[3:4] == 'D':
fdict['mismatch'].append('device major/minor number')
if line[4:5] == 'L':
fdict['mismatch'].append('readlink path')
if line[5:6] == 'U':
fdict['mismatch'].append('user')
if line[6:7] == 'G':
fdict['mismatch'].append('group')
if line[7:8] == 'T':
fdict['mismatch'].append('mtime')
if line[8:9] == 'P':
fdict['mismatch'].append('capabilities')
ret[fname] = fdict
return ret | python | def verify(*packages, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
root
use root as top level directory (default: "/")
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument
CLI Example:
.. code-block:: bash
salt '*' lowpkg.verify
salt '*' lowpkg.verify httpd
salt '*' lowpkg.verify httpd postfix
salt '*' lowpkg.verify httpd postfix ignore_types=['config','doc']
'''
ftypes = {'c': 'config',
'd': 'doc',
'g': 'ghost',
'l': 'license',
'r': 'readme'}
ret = {}
ignore_types = kwargs.get('ignore_types', [])
if not isinstance(ignore_types, (list, six.string_types)):
raise SaltInvocationError(
'ignore_types must be a list or a comma-separated string'
)
if isinstance(ignore_types, six.string_types):
try:
ignore_types = [x.strip() for x in ignore_types.split(',')]
except AttributeError:
ignore_types = [x.strip() for x in six.text_type(ignore_types).split(',')]
verify_options = kwargs.get('verify_options', [])
if not isinstance(verify_options, (list, six.string_types)):
raise SaltInvocationError(
'verify_options must be a list or a comma-separated string'
)
if isinstance(verify_options, six.string_types):
try:
verify_options = [x.strip() for x in verify_options.split(',')]
except AttributeError:
verify_options = [x.strip() for x in six.text_type(verify_options).split(',')]
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['--' + x for x in verify_options])
if packages:
cmd.append('-V')
# Can't concatenate a tuple, must do a list.extend()
cmd.extend(packages)
else:
cmd.append('-Va')
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if not out['stdout'].strip() and out['retcode'] != 0:
# If there is no stdout and the retcode is 0, then verification
# succeeded, but if the retcode is nonzero, then the command failed.
msg = 'Failed to verify package(s)'
if out['stderr']:
msg += ': {0}'.format(out['stderr'])
raise CommandExecutionError(msg)
for line in salt.utils.itertools.split(out['stdout'], '\n'):
fdict = {'mismatch': []}
if 'missing' in line:
line = ' ' + line
fdict['missing'] = True
del fdict['mismatch']
fname = line[13:]
if line[11:12] in ftypes:
fdict['type'] = ftypes[line[11:12]]
if 'type' not in fdict or fdict['type'] not in ignore_types:
if line[0:1] == 'S':
fdict['mismatch'].append('size')
if line[1:2] == 'M':
fdict['mismatch'].append('mode')
if line[2:3] == '5':
fdict['mismatch'].append('md5sum')
if line[3:4] == 'D':
fdict['mismatch'].append('device major/minor number')
if line[4:5] == 'L':
fdict['mismatch'].append('readlink path')
if line[5:6] == 'U':
fdict['mismatch'].append('user')
if line[6:7] == 'G':
fdict['mismatch'].append('group')
if line[7:8] == 'T':
fdict['mismatch'].append('mtime')
if line[8:9] == 'P':
fdict['mismatch'].append('capabilities')
ret[fname] = fdict
return ret | [
"def",
"verify",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"ftypes",
"=",
"{",
"'c'",
":",
"'config'",
",",
"'d'",
":",
"'doc'",
",",
"'g'",
":",
"'ghost'",
",",
"'l'",
":",
"'license'",
",",
"'r'",
":",
"'readme'",
"}",
"ret",
"="... | Runs an rpm -Va on a system, and returns the results in a dict
root
use root as top level directory (default: "/")
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument
CLI Example:
.. code-block:: bash
salt '*' lowpkg.verify
salt '*' lowpkg.verify httpd
salt '*' lowpkg.verify httpd postfix
salt '*' lowpkg.verify httpd postfix ignore_types=['config','doc'] | [
"Runs",
"an",
"rpm",
"-",
"Va",
"on",
"a",
"system",
"and",
"returns",
"the",
"results",
"in",
"a",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L163-L262 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | modified | def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
root
use root as top level directory (default: "/")
CLI examples:
.. code-block:: bash
salt '*' lowpkg.modified httpd
salt '*' lowpkg.modified httpd postfix
salt '*' lowpkg.modified
'''
cmd = ['rpm']
if flags.get('root'):
cmd.extend(['--root', flags.pop('root')])
cmd.append('-Va')
cmd.extend(packages)
ret = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False)
data = {}
# If verification has an output, then it means it failed
# and the return code will be 1. We are interested in any bigger
# than 1 code.
if ret['retcode'] > 1:
del ret['stdout']
return ret
elif not ret['retcode']:
return data
ptrn = re.compile(r"\s+")
changes = cfg = f_name = None
for f_info in salt.utils.itertools.split(ret['stdout'], '\n'):
f_info = ptrn.split(f_info)
if len(f_info) == 3: # Config file
changes, cfg, f_name = f_info
else:
changes, f_name = f_info
cfg = None
keys = ['size', 'mode', 'checksum', 'device', 'symlink',
'owner', 'group', 'time', 'capabilities']
changes = list(changes)
if len(changes) == 8: # Older RPMs do not support capabilities
changes.append('.')
stats = []
for k, v in zip(keys, changes):
if v != '.':
stats.append(k)
if cfg is not None:
stats.append('config')
data[f_name] = stats
if not flags:
return data
# Filtering
filtered_data = {}
for f_name, stats in data.items():
include = True
for param, pval in flags.items():
if param.startswith("_"):
continue
if (not pval and param in stats) or \
(pval and param not in stats):
include = False
break
if include:
filtered_data[f_name] = stats
return filtered_data | python | def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
root
use root as top level directory (default: "/")
CLI examples:
.. code-block:: bash
salt '*' lowpkg.modified httpd
salt '*' lowpkg.modified httpd postfix
salt '*' lowpkg.modified
'''
cmd = ['rpm']
if flags.get('root'):
cmd.extend(['--root', flags.pop('root')])
cmd.append('-Va')
cmd.extend(packages)
ret = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False)
data = {}
# If verification has an output, then it means it failed
# and the return code will be 1. We are interested in any bigger
# than 1 code.
if ret['retcode'] > 1:
del ret['stdout']
return ret
elif not ret['retcode']:
return data
ptrn = re.compile(r"\s+")
changes = cfg = f_name = None
for f_info in salt.utils.itertools.split(ret['stdout'], '\n'):
f_info = ptrn.split(f_info)
if len(f_info) == 3: # Config file
changes, cfg, f_name = f_info
else:
changes, f_name = f_info
cfg = None
keys = ['size', 'mode', 'checksum', 'device', 'symlink',
'owner', 'group', 'time', 'capabilities']
changes = list(changes)
if len(changes) == 8: # Older RPMs do not support capabilities
changes.append('.')
stats = []
for k, v in zip(keys, changes):
if v != '.':
stats.append(k)
if cfg is not None:
stats.append('config')
data[f_name] = stats
if not flags:
return data
# Filtering
filtered_data = {}
for f_name, stats in data.items():
include = True
for param, pval in flags.items():
if param.startswith("_"):
continue
if (not pval and param in stats) or \
(pval and param not in stats):
include = False
break
if include:
filtered_data[f_name] = stats
return filtered_data | [
"def",
"modified",
"(",
"*",
"packages",
",",
"*",
"*",
"flags",
")",
":",
"cmd",
"=",
"[",
"'rpm'",
"]",
"if",
"flags",
".",
"get",
"(",
"'root'",
")",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--root'",
",",
"flags",
".",
"pop",
"(",
"'root'",
"... | List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
root
use root as top level directory (default: "/")
CLI examples:
.. code-block:: bash
salt '*' lowpkg.modified httpd
salt '*' lowpkg.modified httpd postfix
salt '*' lowpkg.modified | [
"List",
"the",
"modified",
"files",
"that",
"belong",
"to",
"a",
"package",
".",
"Not",
"specifying",
"any",
"packages",
"will",
"return",
"a",
"list",
"of",
"_all_",
"modified",
"files",
"on",
"the",
"system",
"s",
"RPM",
"database",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L265-L340 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | file_list | def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's rpm database (not generally
recommended).
root
use root as top level directory (default: "/")
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt '*' lowpkg.file_list httpd postfix
salt '*' lowpkg.file_list
'''
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.append('-ql' if packages else '-qla')
if packages:
# Can't concatenate a tuple, must do a list.extend()
cmd.extend(packages)
ret = __salt__['cmd.run'](
cmd,
output_loglevel='trace',
python_shell=False).splitlines()
return {'errors': [], 'files': ret} | python | def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's rpm database (not generally
recommended).
root
use root as top level directory (default: "/")
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt '*' lowpkg.file_list httpd postfix
salt '*' lowpkg.file_list
'''
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.append('-ql' if packages else '-qla')
if packages:
# Can't concatenate a tuple, must do a list.extend()
cmd.extend(packages)
ret = __salt__['cmd.run'](
cmd,
output_loglevel='trace',
python_shell=False).splitlines()
return {'errors': [], 'files': ret} | [
"def",
"file_list",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"[",
"'rpm'",
"]",
"if",
"kwargs",
".",
"get",
"(",
"'root'",
")",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--root'",
",",
"kwargs",
"[",
"'root'",
"]",
"]",
... | List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's rpm database (not generally
recommended).
root
use root as top level directory (default: "/")
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt '*' lowpkg.file_list httpd postfix
salt '*' lowpkg.file_list | [
"List",
"the",
"files",
"that",
"belong",
"to",
"a",
"package",
".",
"Not",
"specifying",
"any",
"packages",
"will",
"return",
"a",
"list",
"of",
"_every_",
"file",
"on",
"the",
"system",
"s",
"rpm",
"database",
"(",
"not",
"generally",
"recommended",
")",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L343-L373 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | file_dict | def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, sorted by group. Not specifying
any packages will return a list of _every_ file on the system's rpm
database (not generally recommended).
root
use root as top level directory (default: "/")
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_dict httpd
salt '*' lowpkg.file_dict httpd postfix
salt '*' lowpkg.file_dict
'''
errors = []
ret = {}
pkgs = {}
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-q' if packages else '-qa',
'--queryformat', r'%{NAME} %{VERSION}\n'])
if packages:
cmd.extend(packages)
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if 'is not installed' in line:
errors.append(line)
continue
comps = line.split()
pkgs[comps[0]] = {'version': comps[1]}
for pkg in pkgs:
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-ql', pkg])
out = __salt__['cmd.run'](
['rpm', '-ql', pkg],
output_loglevel='trace',
python_shell=False)
ret[pkg] = out.splitlines()
return {'errors': errors, 'packages': ret} | python | def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, sorted by group. Not specifying
any packages will return a list of _every_ file on the system's rpm
database (not generally recommended).
root
use root as top level directory (default: "/")
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_dict httpd
salt '*' lowpkg.file_dict httpd postfix
salt '*' lowpkg.file_dict
'''
errors = []
ret = {}
pkgs = {}
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-q' if packages else '-qa',
'--queryformat', r'%{NAME} %{VERSION}\n'])
if packages:
cmd.extend(packages)
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if 'is not installed' in line:
errors.append(line)
continue
comps = line.split()
pkgs[comps[0]] = {'version': comps[1]}
for pkg in pkgs:
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-ql', pkg])
out = __salt__['cmd.run'](
['rpm', '-ql', pkg],
output_loglevel='trace',
python_shell=False)
ret[pkg] = out.splitlines()
return {'errors': errors, 'packages': ret} | [
"def",
"file_dict",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"ret",
"=",
"{",
"}",
"pkgs",
"=",
"{",
"}",
"cmd",
"=",
"[",
"'rpm'",
"]",
"if",
"kwargs",
".",
"get",
"(",
"'root'",
")",
":",
"cmd",
".",... | List the files that belong to a package, sorted by group. Not specifying
any packages will return a list of _every_ file on the system's rpm
database (not generally recommended).
root
use root as top level directory (default: "/")
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_dict httpd
salt '*' lowpkg.file_dict httpd postfix
salt '*' lowpkg.file_dict | [
"List",
"the",
"files",
"that",
"belong",
"to",
"a",
"package",
"sorted",
"by",
"group",
".",
"Not",
"specifying",
"any",
"packages",
"will",
"return",
"a",
"list",
"of",
"_every_",
"file",
"on",
"the",
"system",
"s",
"rpm",
"database",
"(",
"not",
"gene... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L376-L420 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | owner | def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name pairs
will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
root
use root as top level directory (default: "/")
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.owner /usr/bin/apachectl
salt '*' lowpkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-qf', '--queryformat', '%{name}', path])
ret[path] = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if 'not owned' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return list(ret.values())[0]
return ret | python | def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name pairs
will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
root
use root as top level directory (default: "/")
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.owner /usr/bin/apachectl
salt '*' lowpkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-qf', '--queryformat', '%{name}', path])
ret[path] = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if 'not owned' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return list(ret.values())[0]
return ret | [
"def",
"owner",
"(",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"paths",
":",
"return",
"''",
"ret",
"=",
"{",
"}",
"for",
"path",
"in",
"paths",
":",
"cmd",
"=",
"[",
"'rpm'",
"]",
"if",
"kwargs",
".",
"get",
"(",
"'root'",
... | Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name pairs
will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
root
use root as top level directory (default: "/")
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.owner /usr/bin/apachectl
salt '*' lowpkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf | [
"Return",
"the",
"name",
"of",
"the",
"package",
"that",
"owns",
"the",
"file",
".",
"Multiple",
"file",
"paths",
"can",
"be",
"passed",
".",
"If",
"a",
"single",
"path",
"is",
"passed",
"a",
"string",
"will",
"be",
"returned",
"and",
"if",
"multiple",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L423-L458 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | diff | def diff(package_path, path):
'''
Return a formatted diff between current file and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
:param package: Full pack of the RPM file
:param path: Full path to the installed file
:return: Difference or empty string. For binary files only a notification.
CLI example:
.. code-block:: bash
salt '*' lowpkg.diff /path/to/apache2.rpm /etc/apache2/httpd.conf
'''
cmd = "rpm2cpio {0} " \
"| cpio -i --quiet --to-stdout .{1} " \
"| diff -u --label 'A {1}' --from-file=- --label 'B {1}' {1}"
res = __salt__['cmd.shell'](cmd.format(package_path, path),
output_loglevel='trace')
if res and res.startswith('Binary file'):
return 'File \'{0}\' is binary and its content has been ' \
'modified.'.format(path)
return res | python | def diff(package_path, path):
'''
Return a formatted diff between current file and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
:param package: Full pack of the RPM file
:param path: Full path to the installed file
:return: Difference or empty string. For binary files only a notification.
CLI example:
.. code-block:: bash
salt '*' lowpkg.diff /path/to/apache2.rpm /etc/apache2/httpd.conf
'''
cmd = "rpm2cpio {0} " \
"| cpio -i --quiet --to-stdout .{1} " \
"| diff -u --label 'A {1}' --from-file=- --label 'B {1}' {1}"
res = __salt__['cmd.shell'](cmd.format(package_path, path),
output_loglevel='trace')
if res and res.startswith('Binary file'):
return 'File \'{0}\' is binary and its content has been ' \
'modified.'.format(path)
return res | [
"def",
"diff",
"(",
"package_path",
",",
"path",
")",
":",
"cmd",
"=",
"\"rpm2cpio {0} \"",
"\"| cpio -i --quiet --to-stdout .{1} \"",
"\"| diff -u --label 'A {1}' --from-file=- --label 'B {1}' {1}\"",
"res",
"=",
"__salt__",
"[",
"'cmd.shell'",
"]",
"(",
"cmd",
".",
"for... | Return a formatted diff between current file and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
:param package: Full pack of the RPM file
:param path: Full path to the installed file
:return: Difference or empty string. For binary files only a notification.
CLI example:
.. code-block:: bash
salt '*' lowpkg.diff /path/to/apache2.rpm /etc/apache2/httpd.conf | [
"Return",
"a",
"formatted",
"diff",
"between",
"current",
"file",
"and",
"original",
"in",
"a",
"package",
".",
"NOTE",
":",
"this",
"function",
"includes",
"all",
"files",
"(",
"configuration",
"and",
"not",
")",
"but",
"does",
"not",
"work",
"on",
"binar... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L464-L490 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | info | def info(*packages, **kwargs):
'''
Return a detailed package(s) summary information.
If no packages specified, all packages will be returned.
:param packages:
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
:param all_versions:
Return information for all installed versions of the packages
:param root:
use root as top level directory (default: "/")
:return:
CLI example:
.. code-block:: bash
salt '*' lowpkg.info apache2 bash
salt '*' lowpkg.info apache2 bash attr=version
salt '*' lowpkg.info apache2 bash attr=version,build_date_iso,size
salt '*' lowpkg.info apache2 bash attr=version,build_date_iso,size all_versions=True
'''
all_versions = kwargs.get('all_versions', False)
# LONGSIZE is not a valid tag for all versions of rpm. If LONGSIZE isn't
# available, then we can just use SIZE for older versions. See Issue #31366.
rpm_tags = __salt__['cmd.run_stdout'](
['rpm', '--querytags'],
python_shell=False).splitlines()
if 'LONGSIZE' in rpm_tags:
size_tag = '%{LONGSIZE}'
else:
size_tag = '%{SIZE}'
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
if packages:
cmd.append('-q')
cmd.extend(packages)
else:
cmd.append('-qa')
# Construct query format
attr_map = {
"name": "name: %{NAME}\\n",
"relocations": "relocations: %|PREFIXES?{[%{PREFIXES} ]}:{(not relocatable)}|\\n",
"version": "version: %{VERSION}\\n",
"vendor": "vendor: %{VENDOR}\\n",
"release": "release: %{RELEASE}\\n",
"epoch": "%|EPOCH?{epoch: %{EPOCH}\\n}|",
"build_date_time_t": "build_date_time_t: %{BUILDTIME}\\n",
"build_date": "build_date: %{BUILDTIME}\\n",
"install_date_time_t": "install_date_time_t: %|INSTALLTIME?{%{INSTALLTIME}}:{(not installed)}|\\n",
"install_date": "install_date: %|INSTALLTIME?{%{INSTALLTIME}}:{(not installed)}|\\n",
"build_host": "build_host: %{BUILDHOST}\\n",
"group": "group: %{GROUP}\\n",
"source_rpm": "source_rpm: %{SOURCERPM}\\n",
"size": "size: " + size_tag + "\\n",
"arch": "arch: %{ARCH}\\n",
"license": "%|LICENSE?{license: %{LICENSE}\\n}|",
"signature": "signature: %|DSAHEADER?{%{DSAHEADER:pgpsig}}:{%|RSAHEADER?{%{RSAHEADER:pgpsig}}:"
"{%|SIGGPG?{%{SIGGPG:pgpsig}}:{%|SIGPGP?{%{SIGPGP:pgpsig}}:{(none)}|}|}|}|\\n",
"packager": "%|PACKAGER?{packager: %{PACKAGER}\\n}|",
"url": "%|URL?{url: %{URL}\\n}|",
"summary": "summary: %{SUMMARY}\\n",
"description": "description:\\n%{DESCRIPTION}\\n",
"edition": "edition: %|EPOCH?{%{EPOCH}:}|%{VERSION}-%{RELEASE}\\n",
}
attr = kwargs.get('attr', None) and kwargs['attr'].split(",") or None
query = list()
if attr:
for attr_k in attr:
if attr_k in attr_map and attr_k != 'description':
query.append(attr_map[attr_k])
if not query:
raise CommandExecutionError('No valid attributes found.')
if 'name' not in attr:
attr.append('name')
query.append(attr_map['name'])
if 'edition' not in attr:
attr.append('edition')
query.append(attr_map['edition'])
else:
for attr_k, attr_v in six.iteritems(attr_map):
if attr_k != 'description':
query.append(attr_v)
if attr and 'description' in attr or not attr:
query.append(attr_map['description'])
query.append("-----\\n")
cmd = ' '.join(cmd)
call = __salt__['cmd.run_all'](cmd + (" --queryformat '{0}'".format(''.join(query))),
output_loglevel='trace', env={'TZ': 'UTC'}, clean_env=True)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += (call['stderr'] or call['stdout'])
raise CommandExecutionError(comment)
elif 'error' in call['stderr']:
raise CommandExecutionError(call['stderr'])
else:
out = call['stdout']
_ret = list()
for pkg_info in re.split(r"----*", out):
pkg_info = pkg_info.strip()
if not pkg_info:
continue
pkg_info = pkg_info.split(os.linesep)
if pkg_info[-1].lower().startswith('distribution'):
pkg_info = pkg_info[:-1]
pkg_data = dict()
pkg_name = None
descr_marker = False
descr = list()
for line in pkg_info:
if descr_marker:
descr.append(line)
continue
line = [item.strip() for item in line.split(':', 1)]
if len(line) != 2:
continue
key, value = line
if key == 'description':
descr_marker = True
continue
if key == 'name':
pkg_name = value
# Convert Unix ticks into ISO time format
if key in ['build_date', 'install_date']:
try:
pkg_data[key] = datetime.datetime.utcfromtimestamp(int(value)).isoformat() + "Z"
except ValueError:
log.warning('Could not convert "%s" into Unix time', value)
continue
# Convert Unix ticks into an Integer
if key in ['build_date_time_t', 'install_date_time_t']:
try:
pkg_data[key] = int(value)
except ValueError:
log.warning('Could not convert "%s" into Unix time', value)
continue
if key not in ['description', 'name'] and value:
pkg_data[key] = value
if attr and 'description' in attr or not attr:
pkg_data['description'] = os.linesep.join(descr)
if pkg_name:
pkg_data['name'] = pkg_name
_ret.append(pkg_data)
# Force-sort package data by version,
# pick only latest versions
# (in case multiple packages installed, e.g. kernel)
ret = dict()
for pkg_data in reversed(sorted(_ret, key=lambda x: LooseVersion(x['edition']))):
pkg_name = pkg_data.pop('name')
# Filter out GPG public keys packages
if pkg_name.startswith('gpg-pubkey'):
continue
if pkg_name not in ret:
if all_versions:
ret[pkg_name] = [pkg_data.copy()]
else:
ret[pkg_name] = pkg_data.copy()
del ret[pkg_name]['edition']
elif all_versions:
ret[pkg_name].append(pkg_data.copy())
return ret | python | def info(*packages, **kwargs):
'''
Return a detailed package(s) summary information.
If no packages specified, all packages will be returned.
:param packages:
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
:param all_versions:
Return information for all installed versions of the packages
:param root:
use root as top level directory (default: "/")
:return:
CLI example:
.. code-block:: bash
salt '*' lowpkg.info apache2 bash
salt '*' lowpkg.info apache2 bash attr=version
salt '*' lowpkg.info apache2 bash attr=version,build_date_iso,size
salt '*' lowpkg.info apache2 bash attr=version,build_date_iso,size all_versions=True
'''
all_versions = kwargs.get('all_versions', False)
# LONGSIZE is not a valid tag for all versions of rpm. If LONGSIZE isn't
# available, then we can just use SIZE for older versions. See Issue #31366.
rpm_tags = __salt__['cmd.run_stdout'](
['rpm', '--querytags'],
python_shell=False).splitlines()
if 'LONGSIZE' in rpm_tags:
size_tag = '%{LONGSIZE}'
else:
size_tag = '%{SIZE}'
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
if packages:
cmd.append('-q')
cmd.extend(packages)
else:
cmd.append('-qa')
# Construct query format
attr_map = {
"name": "name: %{NAME}\\n",
"relocations": "relocations: %|PREFIXES?{[%{PREFIXES} ]}:{(not relocatable)}|\\n",
"version": "version: %{VERSION}\\n",
"vendor": "vendor: %{VENDOR}\\n",
"release": "release: %{RELEASE}\\n",
"epoch": "%|EPOCH?{epoch: %{EPOCH}\\n}|",
"build_date_time_t": "build_date_time_t: %{BUILDTIME}\\n",
"build_date": "build_date: %{BUILDTIME}\\n",
"install_date_time_t": "install_date_time_t: %|INSTALLTIME?{%{INSTALLTIME}}:{(not installed)}|\\n",
"install_date": "install_date: %|INSTALLTIME?{%{INSTALLTIME}}:{(not installed)}|\\n",
"build_host": "build_host: %{BUILDHOST}\\n",
"group": "group: %{GROUP}\\n",
"source_rpm": "source_rpm: %{SOURCERPM}\\n",
"size": "size: " + size_tag + "\\n",
"arch": "arch: %{ARCH}\\n",
"license": "%|LICENSE?{license: %{LICENSE}\\n}|",
"signature": "signature: %|DSAHEADER?{%{DSAHEADER:pgpsig}}:{%|RSAHEADER?{%{RSAHEADER:pgpsig}}:"
"{%|SIGGPG?{%{SIGGPG:pgpsig}}:{%|SIGPGP?{%{SIGPGP:pgpsig}}:{(none)}|}|}|}|\\n",
"packager": "%|PACKAGER?{packager: %{PACKAGER}\\n}|",
"url": "%|URL?{url: %{URL}\\n}|",
"summary": "summary: %{SUMMARY}\\n",
"description": "description:\\n%{DESCRIPTION}\\n",
"edition": "edition: %|EPOCH?{%{EPOCH}:}|%{VERSION}-%{RELEASE}\\n",
}
attr = kwargs.get('attr', None) and kwargs['attr'].split(",") or None
query = list()
if attr:
for attr_k in attr:
if attr_k in attr_map and attr_k != 'description':
query.append(attr_map[attr_k])
if not query:
raise CommandExecutionError('No valid attributes found.')
if 'name' not in attr:
attr.append('name')
query.append(attr_map['name'])
if 'edition' not in attr:
attr.append('edition')
query.append(attr_map['edition'])
else:
for attr_k, attr_v in six.iteritems(attr_map):
if attr_k != 'description':
query.append(attr_v)
if attr and 'description' in attr or not attr:
query.append(attr_map['description'])
query.append("-----\\n")
cmd = ' '.join(cmd)
call = __salt__['cmd.run_all'](cmd + (" --queryformat '{0}'".format(''.join(query))),
output_loglevel='trace', env={'TZ': 'UTC'}, clean_env=True)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += (call['stderr'] or call['stdout'])
raise CommandExecutionError(comment)
elif 'error' in call['stderr']:
raise CommandExecutionError(call['stderr'])
else:
out = call['stdout']
_ret = list()
for pkg_info in re.split(r"----*", out):
pkg_info = pkg_info.strip()
if not pkg_info:
continue
pkg_info = pkg_info.split(os.linesep)
if pkg_info[-1].lower().startswith('distribution'):
pkg_info = pkg_info[:-1]
pkg_data = dict()
pkg_name = None
descr_marker = False
descr = list()
for line in pkg_info:
if descr_marker:
descr.append(line)
continue
line = [item.strip() for item in line.split(':', 1)]
if len(line) != 2:
continue
key, value = line
if key == 'description':
descr_marker = True
continue
if key == 'name':
pkg_name = value
# Convert Unix ticks into ISO time format
if key in ['build_date', 'install_date']:
try:
pkg_data[key] = datetime.datetime.utcfromtimestamp(int(value)).isoformat() + "Z"
except ValueError:
log.warning('Could not convert "%s" into Unix time', value)
continue
# Convert Unix ticks into an Integer
if key in ['build_date_time_t', 'install_date_time_t']:
try:
pkg_data[key] = int(value)
except ValueError:
log.warning('Could not convert "%s" into Unix time', value)
continue
if key not in ['description', 'name'] and value:
pkg_data[key] = value
if attr and 'description' in attr or not attr:
pkg_data['description'] = os.linesep.join(descr)
if pkg_name:
pkg_data['name'] = pkg_name
_ret.append(pkg_data)
# Force-sort package data by version,
# pick only latest versions
# (in case multiple packages installed, e.g. kernel)
ret = dict()
for pkg_data in reversed(sorted(_ret, key=lambda x: LooseVersion(x['edition']))):
pkg_name = pkg_data.pop('name')
# Filter out GPG public keys packages
if pkg_name.startswith('gpg-pubkey'):
continue
if pkg_name not in ret:
if all_versions:
ret[pkg_name] = [pkg_data.copy()]
else:
ret[pkg_name] = pkg_data.copy()
del ret[pkg_name]['edition']
elif all_versions:
ret[pkg_name].append(pkg_data.copy())
return ret | [
"def",
"info",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"all_versions",
"=",
"kwargs",
".",
"get",
"(",
"'all_versions'",
",",
"False",
")",
"# LONGSIZE is not a valid tag for all versions of rpm. If LONGSIZE isn't",
"# available, then we can just use SIZE... | Return a detailed package(s) summary information.
If no packages specified, all packages will be returned.
:param packages:
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
:param all_versions:
Return information for all installed versions of the packages
:param root:
use root as top level directory (default: "/")
:return:
CLI example:
.. code-block:: bash
salt '*' lowpkg.info apache2 bash
salt '*' lowpkg.info apache2 bash attr=version
salt '*' lowpkg.info apache2 bash attr=version,build_date_iso,size
salt '*' lowpkg.info apache2 bash attr=version,build_date_iso,size all_versions=True | [
"Return",
"a",
"detailed",
"package",
"(",
"s",
")",
"summary",
"information",
".",
"If",
"no",
"packages",
"specified",
"all",
"packages",
"will",
"be",
"returned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L493-L674 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | version_cmp | def version_cmp(ver1, ver2, ignore_epoch=False):
'''
.. versionadded:: 2015.8.9
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch \
else six.text_type(x)
ver1 = normalize(ver1)
ver2 = normalize(ver2)
try:
cmp_func = None
if HAS_RPM:
try:
cmp_func = rpm.labelCompare
except AttributeError:
# Catches corner case where someone has a module named "rpm" in
# their pythonpath.
log.debug(
'rpm module imported, but it does not have the '
'labelCompare function. Not using rpm.labelCompare for '
'version comparison.'
)
if cmp_func is None and HAS_RPMUTILS:
try:
cmp_func = rpmUtils.miscutils.compareEVR
except AttributeError:
log.debug('rpmUtils.miscutils.compareEVR is not available')
if cmp_func is None:
if salt.utils.path.which('rpmdev-vercmp'):
# rpmdev-vercmp always uses epochs, even when zero
def _ensure_epoch(ver):
def _prepend(ver):
return '0:{0}'.format(ver)
try:
if ':' not in ver:
return _prepend(ver)
except TypeError:
return _prepend(ver)
return ver
ver1 = _ensure_epoch(ver1)
ver2 = _ensure_epoch(ver2)
result = __salt__['cmd.run_all'](
['rpmdev-vercmp', ver1, ver2],
python_shell=False,
redirect_stderr=True,
ignore_retcode=True)
# rpmdev-vercmp returns 0 on equal, 11 on greater-than, and
# 12 on less-than.
if result['retcode'] == 0:
return 0
elif result['retcode'] == 11:
return 1
elif result['retcode'] == 12:
return -1
else:
# We'll need to fall back to salt.utils.versions.version_cmp()
log.warning(
'Failed to interpret results of rpmdev-vercmp output. '
'This is probably a bug, and should be reported. '
'Return code was %s. Output: %s',
result['retcode'], result['stdout']
)
else:
# We'll need to fall back to salt.utils.versions.version_cmp()
log.warning(
'rpmdevtools is not installed, please install it for '
'more accurate version comparisons'
)
else:
# If one EVR is missing a release but not the other and they
# otherwise would be equal, ignore the release. This can happen if
# e.g. you are checking if a package version 3.2 is satisfied by
# 3.2-1.
(ver1_e, ver1_v, ver1_r) = salt.utils.pkg.rpm.version_to_evr(ver1)
(ver2_e, ver2_v, ver2_r) = salt.utils.pkg.rpm.version_to_evr(ver2)
if not ver1_r or not ver2_r:
ver1_r = ver2_r = ''
cmp_result = cmp_func((ver1_e, ver1_v, ver1_r),
(ver2_e, ver2_v, ver2_r))
if cmp_result not in (-1, 0, 1):
raise CommandExecutionError(
'Comparison result \'{0}\' is invalid'.format(cmp_result)
)
return cmp_result
except Exception as exc:
log.warning(
'Failed to compare version \'%s\' to \'%s\' using RPM: %s',
ver1, ver2, exc
)
# We would already have normalized the versions at the beginning of this
# function if ignore_epoch=True, so avoid unnecessary work and just pass
# False for this value.
return salt.utils.versions.version_cmp(ver1, ver2, ignore_epoch=False) | python | def version_cmp(ver1, ver2, ignore_epoch=False):
'''
.. versionadded:: 2015.8.9
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch \
else six.text_type(x)
ver1 = normalize(ver1)
ver2 = normalize(ver2)
try:
cmp_func = None
if HAS_RPM:
try:
cmp_func = rpm.labelCompare
except AttributeError:
# Catches corner case where someone has a module named "rpm" in
# their pythonpath.
log.debug(
'rpm module imported, but it does not have the '
'labelCompare function. Not using rpm.labelCompare for '
'version comparison.'
)
if cmp_func is None and HAS_RPMUTILS:
try:
cmp_func = rpmUtils.miscutils.compareEVR
except AttributeError:
log.debug('rpmUtils.miscutils.compareEVR is not available')
if cmp_func is None:
if salt.utils.path.which('rpmdev-vercmp'):
# rpmdev-vercmp always uses epochs, even when zero
def _ensure_epoch(ver):
def _prepend(ver):
return '0:{0}'.format(ver)
try:
if ':' not in ver:
return _prepend(ver)
except TypeError:
return _prepend(ver)
return ver
ver1 = _ensure_epoch(ver1)
ver2 = _ensure_epoch(ver2)
result = __salt__['cmd.run_all'](
['rpmdev-vercmp', ver1, ver2],
python_shell=False,
redirect_stderr=True,
ignore_retcode=True)
# rpmdev-vercmp returns 0 on equal, 11 on greater-than, and
# 12 on less-than.
if result['retcode'] == 0:
return 0
elif result['retcode'] == 11:
return 1
elif result['retcode'] == 12:
return -1
else:
# We'll need to fall back to salt.utils.versions.version_cmp()
log.warning(
'Failed to interpret results of rpmdev-vercmp output. '
'This is probably a bug, and should be reported. '
'Return code was %s. Output: %s',
result['retcode'], result['stdout']
)
else:
# We'll need to fall back to salt.utils.versions.version_cmp()
log.warning(
'rpmdevtools is not installed, please install it for '
'more accurate version comparisons'
)
else:
# If one EVR is missing a release but not the other and they
# otherwise would be equal, ignore the release. This can happen if
# e.g. you are checking if a package version 3.2 is satisfied by
# 3.2-1.
(ver1_e, ver1_v, ver1_r) = salt.utils.pkg.rpm.version_to_evr(ver1)
(ver2_e, ver2_v, ver2_r) = salt.utils.pkg.rpm.version_to_evr(ver2)
if not ver1_r or not ver2_r:
ver1_r = ver2_r = ''
cmp_result = cmp_func((ver1_e, ver1_v, ver1_r),
(ver2_e, ver2_v, ver2_r))
if cmp_result not in (-1, 0, 1):
raise CommandExecutionError(
'Comparison result \'{0}\' is invalid'.format(cmp_result)
)
return cmp_result
except Exception as exc:
log.warning(
'Failed to compare version \'%s\' to \'%s\' using RPM: %s',
ver1, ver2, exc
)
# We would already have normalized the versions at the beginning of this
# function if ignore_epoch=True, so avoid unnecessary work and just pass
# False for this value.
return salt.utils.versions.version_cmp(ver1, ver2, ignore_epoch=False) | [
"def",
"version_cmp",
"(",
"ver1",
",",
"ver2",
",",
"ignore_epoch",
"=",
"False",
")",
":",
"normalize",
"=",
"lambda",
"x",
":",
"six",
".",
"text_type",
"(",
"x",
")",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"-",
"1",
"]",
"if",
"ignore_... | .. versionadded:: 2015.8.9
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002' | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"9"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L677-L791 | train |
saltstack/salt | salt/modules/rpm_lowpkg.py | checksum | def checksum(*paths, **kwargs):
'''
Return if the signature of a RPM file is valid.
root
use root as top level directory (default: "/")
CLI Example:
.. code-block:: bash
salt '*' lowpkg.checksum /path/to/package1.rpm
salt '*' lowpkg.checksum /path/to/package1.rpm /path/to/package2.rpm
'''
ret = dict()
if not paths:
raise CommandExecutionError("No package files has been specified.")
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-K', '--quiet'])
for package_file in paths:
cmd_ = cmd + [package_file]
ret[package_file] = (bool(__salt__['file.file_exists'](package_file)) and
not __salt__['cmd.retcode'](cmd_,
ignore_retcode=True,
output_loglevel='trace',
python_shell=False))
return ret | python | def checksum(*paths, **kwargs):
'''
Return if the signature of a RPM file is valid.
root
use root as top level directory (default: "/")
CLI Example:
.. code-block:: bash
salt '*' lowpkg.checksum /path/to/package1.rpm
salt '*' lowpkg.checksum /path/to/package1.rpm /path/to/package2.rpm
'''
ret = dict()
if not paths:
raise CommandExecutionError("No package files has been specified.")
cmd = ['rpm']
if kwargs.get('root'):
cmd.extend(['--root', kwargs['root']])
cmd.extend(['-K', '--quiet'])
for package_file in paths:
cmd_ = cmd + [package_file]
ret[package_file] = (bool(__salt__['file.file_exists'](package_file)) and
not __salt__['cmd.retcode'](cmd_,
ignore_retcode=True,
output_loglevel='trace',
python_shell=False))
return ret | [
"def",
"checksum",
"(",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"if",
"not",
"paths",
":",
"raise",
"CommandExecutionError",
"(",
"\"No package files has been specified.\"",
")",
"cmd",
"=",
"[",
"'rpm'",
"]",
"if",
... | Return if the signature of a RPM file is valid.
root
use root as top level directory (default: "/")
CLI Example:
.. code-block:: bash
salt '*' lowpkg.checksum /path/to/package1.rpm
salt '*' lowpkg.checksum /path/to/package1.rpm /path/to/package2.rpm | [
"Return",
"if",
"the",
"signature",
"of",
"a",
"RPM",
"file",
"is",
"valid",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rpm_lowpkg.py#L794-L825 | train |
saltstack/salt | salt/modules/haproxyconn.py | _get_conn | def _get_conn(socket=DEFAULT_SOCKET_URL):
'''
Get connection to haproxy socket.
'''
assert os.path.exists(socket), '{0} does not exist.'.format(socket)
issock = os.stat(socket).st_mode
assert stat.S_ISSOCK(issock), '{0} is not a socket.'.format(socket)
ha_conn = haproxy.conn.HaPConn(socket)
return ha_conn | python | def _get_conn(socket=DEFAULT_SOCKET_URL):
'''
Get connection to haproxy socket.
'''
assert os.path.exists(socket), '{0} does not exist.'.format(socket)
issock = os.stat(socket).st_mode
assert stat.S_ISSOCK(issock), '{0} is not a socket.'.format(socket)
ha_conn = haproxy.conn.HaPConn(socket)
return ha_conn | [
"def",
"_get_conn",
"(",
"socket",
"=",
"DEFAULT_SOCKET_URL",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"socket",
")",
",",
"'{0} does not exist.'",
".",
"format",
"(",
"socket",
")",
"issock",
"=",
"os",
".",
"stat",
"(",
"socket",
")",... | Get connection to haproxy socket. | [
"Get",
"connection",
"to",
"haproxy",
"socket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/haproxyconn.py#L44-L52 | train |
saltstack/salt | salt/modules/haproxyconn.py | list_servers | def list_servers(backend, socket=DEFAULT_SOCKET_URL, objectify=False):
'''
List servers in haproxy backend.
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.list_servers mysql
'''
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.listServers(backend=backend)
return ha_conn.sendCmd(ha_cmd, objectify=objectify) | python | def list_servers(backend, socket=DEFAULT_SOCKET_URL, objectify=False):
'''
List servers in haproxy backend.
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.list_servers mysql
'''
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.listServers(backend=backend)
return ha_conn.sendCmd(ha_cmd, objectify=objectify) | [
"def",
"list_servers",
"(",
"backend",
",",
"socket",
"=",
"DEFAULT_SOCKET_URL",
",",
"objectify",
"=",
"False",
")",
":",
"ha_conn",
"=",
"_get_conn",
"(",
"socket",
")",
"ha_cmd",
"=",
"haproxy",
".",
"cmds",
".",
"listServers",
"(",
"backend",
"=",
"bac... | List servers in haproxy backend.
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.list_servers mysql | [
"List",
"servers",
"in",
"haproxy",
"backend",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/haproxyconn.py#L55-L73 | train |
saltstack/salt | salt/modules/haproxyconn.py | enable_server | def enable_server(name, backend, socket=DEFAULT_SOCKET_URL):
'''
Enable Server in haproxy
name
Server to enable
backend
haproxy backend, or all backends if "*" is supplied
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.enable_server web1.example.com www
'''
if backend == '*':
backends = show_backends(socket=socket).split('\n')
else:
backends = [backend]
results = {}
for backend in backends:
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.enableServer(server=name, backend=backend)
ha_conn.sendCmd(ha_cmd)
results[backend] = list_servers(backend, socket=socket)
return results | python | def enable_server(name, backend, socket=DEFAULT_SOCKET_URL):
'''
Enable Server in haproxy
name
Server to enable
backend
haproxy backend, or all backends if "*" is supplied
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.enable_server web1.example.com www
'''
if backend == '*':
backends = show_backends(socket=socket).split('\n')
else:
backends = [backend]
results = {}
for backend in backends:
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.enableServer(server=name, backend=backend)
ha_conn.sendCmd(ha_cmd)
results[backend] = list_servers(backend, socket=socket)
return results | [
"def",
"enable_server",
"(",
"name",
",",
"backend",
",",
"socket",
"=",
"DEFAULT_SOCKET_URL",
")",
":",
"if",
"backend",
"==",
"'*'",
":",
"backends",
"=",
"show_backends",
"(",
"socket",
"=",
"socket",
")",
".",
"split",
"(",
"'\\n'",
")",
"else",
":",... | Enable Server in haproxy
name
Server to enable
backend
haproxy backend, or all backends if "*" is supplied
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.enable_server web1.example.com www | [
"Enable",
"Server",
"in",
"haproxy"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/haproxyconn.py#L158-L190 | train |
saltstack/salt | salt/modules/haproxyconn.py | get_weight | def get_weight(name, backend, socket=DEFAULT_SOCKET_URL):
'''
Get server weight
name
Server name
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.get_weight web1.example.com www
'''
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.getWeight(server=name, backend=backend)
return ha_conn.sendCmd(ha_cmd) | python | def get_weight(name, backend, socket=DEFAULT_SOCKET_URL):
'''
Get server weight
name
Server name
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.get_weight web1.example.com www
'''
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.getWeight(server=name, backend=backend)
return ha_conn.sendCmd(ha_cmd) | [
"def",
"get_weight",
"(",
"name",
",",
"backend",
",",
"socket",
"=",
"DEFAULT_SOCKET_URL",
")",
":",
"ha_conn",
"=",
"_get_conn",
"(",
"socket",
")",
"ha_cmd",
"=",
"haproxy",
".",
"cmds",
".",
"getWeight",
"(",
"server",
"=",
"name",
",",
"backend",
"=... | Get server weight
name
Server name
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.get_weight web1.example.com www | [
"Get",
"server",
"weight"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/haproxyconn.py#L228-L249 | train |
saltstack/salt | salt/modules/haproxyconn.py | set_state | def set_state(name, backend, state, socket=DEFAULT_SOCKET_URL):
'''
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the "enable server" command. Setting the state to "maint" disables any traffic
to the server as well as any health checks. This is the equivalent of the
"disable server" command. Setting the mode to "drain" only removes the server
from load balancing but still allows it to be checked and to accept new
persistent connections. Changes are propagated to tracking servers if any.
name
Server name
backend
haproxy backend
state
A string of the state to set. Must be 'ready', 'drain', or 'maint'
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.set_state my_proxy_server my_backend ready
'''
# Pulling this in from the latest 0.5 release which is not yet in PyPi.
# https://github.com/neurogeek/haproxyctl
class setServerState(haproxy.cmds.Cmd):
"""Set server state command."""
cmdTxt = "set server %(backend)s/%(server)s state %(value)s\r\n"
p_args = ['backend', 'server', 'value']
helpTxt = "Force a server's administrative state to a new state."
ha_conn = _get_conn(socket)
ha_cmd = setServerState(server=name, backend=backend, value=state)
return ha_conn.sendCmd(ha_cmd) | python | def set_state(name, backend, state, socket=DEFAULT_SOCKET_URL):
'''
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the "enable server" command. Setting the state to "maint" disables any traffic
to the server as well as any health checks. This is the equivalent of the
"disable server" command. Setting the mode to "drain" only removes the server
from load balancing but still allows it to be checked and to accept new
persistent connections. Changes are propagated to tracking servers if any.
name
Server name
backend
haproxy backend
state
A string of the state to set. Must be 'ready', 'drain', or 'maint'
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.set_state my_proxy_server my_backend ready
'''
# Pulling this in from the latest 0.5 release which is not yet in PyPi.
# https://github.com/neurogeek/haproxyctl
class setServerState(haproxy.cmds.Cmd):
"""Set server state command."""
cmdTxt = "set server %(backend)s/%(server)s state %(value)s\r\n"
p_args = ['backend', 'server', 'value']
helpTxt = "Force a server's administrative state to a new state."
ha_conn = _get_conn(socket)
ha_cmd = setServerState(server=name, backend=backend, value=state)
return ha_conn.sendCmd(ha_cmd) | [
"def",
"set_state",
"(",
"name",
",",
"backend",
",",
"state",
",",
"socket",
"=",
"DEFAULT_SOCKET_URL",
")",
":",
"# Pulling this in from the latest 0.5 release which is not yet in PyPi.",
"# https://github.com/neurogeek/haproxyctl",
"class",
"setServerState",
"(",
"haproxy",
... | Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the "enable server" command. Setting the state to "maint" disables any traffic
to the server as well as any health checks. This is the equivalent of the
"disable server" command. Setting the mode to "drain" only removes the server
from load balancing but still allows it to be checked and to accept new
persistent connections. Changes are propagated to tracking servers if any.
name
Server name
backend
haproxy backend
state
A string of the state to set. Must be 'ready', 'drain', or 'maint'
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.set_state my_proxy_server my_backend ready | [
"Force",
"a",
"server",
"s",
"administrative",
"state",
"to",
"a",
"new",
"state",
".",
"This",
"can",
"be",
"useful",
"to",
"disable",
"load",
"balancing",
"and",
"/",
"or",
"any",
"traffic",
"to",
"a",
"server",
".",
"Setting",
"the",
"state",
"to",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/haproxyconn.py#L280-L320 | train |
saltstack/salt | salt/modules/haproxyconn.py | show_frontends | def show_frontends(socket=DEFAULT_SOCKET_URL):
'''
Show HaProxy frontends
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.show_frontends
'''
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.showFrontends()
return ha_conn.sendCmd(ha_cmd) | python | def show_frontends(socket=DEFAULT_SOCKET_URL):
'''
Show HaProxy frontends
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.show_frontends
'''
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.showFrontends()
return ha_conn.sendCmd(ha_cmd) | [
"def",
"show_frontends",
"(",
"socket",
"=",
"DEFAULT_SOCKET_URL",
")",
":",
"ha_conn",
"=",
"_get_conn",
"(",
"socket",
")",
"ha_cmd",
"=",
"haproxy",
".",
"cmds",
".",
"showFrontends",
"(",
")",
"return",
"ha_conn",
".",
"sendCmd",
"(",
"ha_cmd",
")"
] | Show HaProxy frontends
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.show_frontends | [
"Show",
"HaProxy",
"frontends"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/haproxyconn.py#L323-L338 | train |
saltstack/salt | salt/modules/haproxyconn.py | show_backends | def show_backends(socket=DEFAULT_SOCKET_URL):
'''
Show HaProxy Backends
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.show_backends
'''
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.showBackends()
return ha_conn.sendCmd(ha_cmd) | python | def show_backends(socket=DEFAULT_SOCKET_URL):
'''
Show HaProxy Backends
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.show_backends
'''
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.showBackends()
return ha_conn.sendCmd(ha_cmd) | [
"def",
"show_backends",
"(",
"socket",
"=",
"DEFAULT_SOCKET_URL",
")",
":",
"ha_conn",
"=",
"_get_conn",
"(",
"socket",
")",
"ha_cmd",
"=",
"haproxy",
".",
"cmds",
".",
"showBackends",
"(",
")",
"return",
"ha_conn",
".",
"sendCmd",
"(",
"ha_cmd",
")"
] | Show HaProxy Backends
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.show_backends | [
"Show",
"HaProxy",
"Backends"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/haproxyconn.py#L358-L373 | train |
saltstack/salt | salt/modules/haproxyconn.py | get_sessions | def get_sessions(name, backend, socket=DEFAULT_SOCKET_URL):
'''
.. versionadded:: 2016.11.0
Get number of current sessions on server in backend (scur)
name
Server name
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.get_sessions web1.example.com www
'''
class getStats(haproxy.cmds.Cmd):
p_args = ["backend", "server"]
cmdTxt = "show stat\r\n"
helpText = "Fetch all statistics"
ha_conn = _get_conn(socket)
ha_cmd = getStats(server=name, backend=backend)
result = ha_conn.sendCmd(ha_cmd)
for line in result.split('\n'):
if line.startswith(backend):
outCols = line.split(',')
if outCols[1] == name:
return outCols[4] | python | def get_sessions(name, backend, socket=DEFAULT_SOCKET_URL):
'''
.. versionadded:: 2016.11.0
Get number of current sessions on server in backend (scur)
name
Server name
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.get_sessions web1.example.com www
'''
class getStats(haproxy.cmds.Cmd):
p_args = ["backend", "server"]
cmdTxt = "show stat\r\n"
helpText = "Fetch all statistics"
ha_conn = _get_conn(socket)
ha_cmd = getStats(server=name, backend=backend)
result = ha_conn.sendCmd(ha_cmd)
for line in result.split('\n'):
if line.startswith(backend):
outCols = line.split(',')
if outCols[1] == name:
return outCols[4] | [
"def",
"get_sessions",
"(",
"name",
",",
"backend",
",",
"socket",
"=",
"DEFAULT_SOCKET_URL",
")",
":",
"class",
"getStats",
"(",
"haproxy",
".",
"cmds",
".",
"Cmd",
")",
":",
"p_args",
"=",
"[",
"\"backend\"",
",",
"\"server\"",
"]",
"cmdTxt",
"=",
"\"s... | .. versionadded:: 2016.11.0
Get number of current sessions on server in backend (scur)
name
Server name
backend
haproxy backend
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block:: bash
salt '*' haproxy.get_sessions web1.example.com www | [
"..",
"versionadded",
"::",
"2016",
".",
"11",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/haproxyconn.py#L402-L435 | train |
saltstack/salt | salt/states/beacon.py | present | def present(name,
save=False,
**kwargs):
'''
Ensure beacon is configured with the included beacon data.
Args:
name (str):
The name of the beacon ensure is configured.
save (bool):
``True`` updates the beacons.conf. Default is ``False``.
Returns:
dict: A dictionary of information about the results of the state
Example:
.. code-block:: yaml
ps_beacon:
beacon.present:
- name: ps
- save: True
- enable: False
- services:
salt-master: running
apache2: stopped
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': []}
current_beacons = __salt__['beacons.list'](return_yaml=False, **kwargs)
beacon_data = [{k: v} for k, v in six.iteritems(kwargs)]
if name in current_beacons:
if beacon_data == current_beacons[name]:
ret['comment'].append('Job {0} in correct state'.format(name))
else:
if 'test' in __opts__ and __opts__['test']:
kwargs['test'] = True
result = __salt__['beacons.modify'](name, beacon_data, **kwargs)
ret['comment'].append(result['comment'])
ret['changes'] = result['changes']
else:
result = __salt__['beacons.modify'](name, beacon_data, **kwargs)
if not result['result']:
ret['result'] = result['result']
ret['comment'] = result['comment']
return ret
else:
if 'changes' in result:
ret['comment'].append('Modifying {0} in beacons'.format(name))
ret['changes'] = result['changes']
else:
ret['comment'].append(result['comment'])
else:
if 'test' in __opts__ and __opts__['test']:
kwargs['test'] = True
result = __salt__['beacons.add'](name, beacon_data, **kwargs)
ret['comment'].append(result['comment'])
else:
result = __salt__['beacons.add'](name, beacon_data, **kwargs)
if not result['result']:
ret['result'] = result['result']
ret['comment'] = result['comment']
return ret
else:
ret['comment'].append('Adding {0} to beacons'.format(name))
if save:
__salt__['beacons.save'](**kwargs)
ret['comment'].append('Beacon {0} saved'.format(name))
ret['comment'] = '\n'.join(ret['comment'])
return ret | python | def present(name,
save=False,
**kwargs):
'''
Ensure beacon is configured with the included beacon data.
Args:
name (str):
The name of the beacon ensure is configured.
save (bool):
``True`` updates the beacons.conf. Default is ``False``.
Returns:
dict: A dictionary of information about the results of the state
Example:
.. code-block:: yaml
ps_beacon:
beacon.present:
- name: ps
- save: True
- enable: False
- services:
salt-master: running
apache2: stopped
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': []}
current_beacons = __salt__['beacons.list'](return_yaml=False, **kwargs)
beacon_data = [{k: v} for k, v in six.iteritems(kwargs)]
if name in current_beacons:
if beacon_data == current_beacons[name]:
ret['comment'].append('Job {0} in correct state'.format(name))
else:
if 'test' in __opts__ and __opts__['test']:
kwargs['test'] = True
result = __salt__['beacons.modify'](name, beacon_data, **kwargs)
ret['comment'].append(result['comment'])
ret['changes'] = result['changes']
else:
result = __salt__['beacons.modify'](name, beacon_data, **kwargs)
if not result['result']:
ret['result'] = result['result']
ret['comment'] = result['comment']
return ret
else:
if 'changes' in result:
ret['comment'].append('Modifying {0} in beacons'.format(name))
ret['changes'] = result['changes']
else:
ret['comment'].append(result['comment'])
else:
if 'test' in __opts__ and __opts__['test']:
kwargs['test'] = True
result = __salt__['beacons.add'](name, beacon_data, **kwargs)
ret['comment'].append(result['comment'])
else:
result = __salt__['beacons.add'](name, beacon_data, **kwargs)
if not result['result']:
ret['result'] = result['result']
ret['comment'] = result['comment']
return ret
else:
ret['comment'].append('Adding {0} to beacons'.format(name))
if save:
__salt__['beacons.save'](**kwargs)
ret['comment'].append('Beacon {0} saved'.format(name))
ret['comment'] = '\n'.join(ret['comment'])
return ret | [
"def",
"present",
"(",
"name",
",",
"save",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"[",
"]",
"}",
"current_bea... | Ensure beacon is configured with the included beacon data.
Args:
name (str):
The name of the beacon ensure is configured.
save (bool):
``True`` updates the beacons.conf. Default is ``False``.
Returns:
dict: A dictionary of information about the results of the state
Example:
.. code-block:: yaml
ps_beacon:
beacon.present:
- name: ps
- save: True
- enable: False
- services:
salt-master: running
apache2: stopped | [
"Ensure",
"beacon",
"is",
"configured",
"with",
"the",
"included",
"beacon",
"data",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/beacon.py#L80-L160 | train |
saltstack/salt | salt/modules/netscaler.py | _connect | def _connect(**kwargs):
'''
Initialise netscaler connection
'''
connargs = dict()
# Shamelessy ripped from the mysql module
def __connarg(name, key=None, default=None):
'''
Add key to connargs, only if name exists in our kwargs or as
netscaler.<name> in __opts__ or __pillar__ Evaluate in said order - kwargs,
opts then pillar. To avoid collision with other functions, kwargs-based
connection arguments are prefixed with 'netscaler_' (i.e.
'netscaler_host', 'netscaler_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = 'netscaler_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('netscaler.{0}'.format(name), None)
if val is not None:
connargs[key] = val
elif default is not None:
connargs[key] = default
__connarg('netscaler_host', 'host')
__connarg('netscaler_user', 'user')
__connarg('netscaler_pass', 'pass')
__connarg('netscaler_useSSL', 'useSSL', True)
nitro = NSNitro(connargs['host'], connargs['user'], connargs['pass'], connargs['useSSL'])
try:
nitro.login()
except NSNitroError as error:
log.debug('netscaler module error - NSNitro.login() failed: %s', error)
return None
return nitro | python | def _connect(**kwargs):
'''
Initialise netscaler connection
'''
connargs = dict()
# Shamelessy ripped from the mysql module
def __connarg(name, key=None, default=None):
'''
Add key to connargs, only if name exists in our kwargs or as
netscaler.<name> in __opts__ or __pillar__ Evaluate in said order - kwargs,
opts then pillar. To avoid collision with other functions, kwargs-based
connection arguments are prefixed with 'netscaler_' (i.e.
'netscaler_host', 'netscaler_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
else:
prefix = 'netscaler_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('netscaler.{0}'.format(name), None)
if val is not None:
connargs[key] = val
elif default is not None:
connargs[key] = default
__connarg('netscaler_host', 'host')
__connarg('netscaler_user', 'user')
__connarg('netscaler_pass', 'pass')
__connarg('netscaler_useSSL', 'useSSL', True)
nitro = NSNitro(connargs['host'], connargs['user'], connargs['pass'], connargs['useSSL'])
try:
nitro.login()
except NSNitroError as error:
log.debug('netscaler module error - NSNitro.login() failed: %s', error)
return None
return nitro | [
"def",
"_connect",
"(",
"*",
"*",
"kwargs",
")",
":",
"connargs",
"=",
"dict",
"(",
")",
"# Shamelessy ripped from the mysql module",
"def",
"__connarg",
"(",
"name",
",",
"key",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"'''\n Add key to conn... | Initialise netscaler connection | [
"Initialise",
"netscaler",
"connection"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L89-L132 | train |
saltstack/salt | salt/modules/netscaler.py | _servicegroup_get | def _servicegroup_get(sg_name, **connection_args):
'''
Return a service group ressource or None
'''
nitro = _connect(**connection_args)
if nitro is None:
return None
sg = NSServiceGroup()
sg.set_servicegroupname(sg_name)
try:
sg = NSServiceGroup.get(nitro, sg)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.get() failed: %s', error)
sg = None
_disconnect(nitro)
return sg | python | def _servicegroup_get(sg_name, **connection_args):
'''
Return a service group ressource or None
'''
nitro = _connect(**connection_args)
if nitro is None:
return None
sg = NSServiceGroup()
sg.set_servicegroupname(sg_name)
try:
sg = NSServiceGroup.get(nitro, sg)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.get() failed: %s', error)
sg = None
_disconnect(nitro)
return sg | [
"def",
"_servicegroup_get",
"(",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
":",
"nitro",
"=",
"_connect",
"(",
"*",
"*",
"connection_args",
")",
"if",
"nitro",
"is",
"None",
":",
"return",
"None",
"sg",
"=",
"NSServiceGroup",
"(",
")",
"sg",
".",... | Return a service group ressource or None | [
"Return",
"a",
"service",
"group",
"ressource",
"or",
"None"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L144-L159 | train |
saltstack/salt | salt/modules/netscaler.py | _servicegroup_get_servers | def _servicegroup_get_servers(sg_name, **connection_args):
'''
Returns a list of members of a servicegroup or None
'''
nitro = _connect(**connection_args)
if nitro is None:
return None
sg = NSServiceGroup()
sg.set_servicegroupname(sg_name)
try:
sg = NSServiceGroup.get_servers(nitro, sg)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.get_servers failed(): %s', error)
sg = None
_disconnect(nitro)
return sg | python | def _servicegroup_get_servers(sg_name, **connection_args):
'''
Returns a list of members of a servicegroup or None
'''
nitro = _connect(**connection_args)
if nitro is None:
return None
sg = NSServiceGroup()
sg.set_servicegroupname(sg_name)
try:
sg = NSServiceGroup.get_servers(nitro, sg)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.get_servers failed(): %s', error)
sg = None
_disconnect(nitro)
return sg | [
"def",
"_servicegroup_get_servers",
"(",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
":",
"nitro",
"=",
"_connect",
"(",
"*",
"*",
"connection_args",
")",
"if",
"nitro",
"is",
"None",
":",
"return",
"None",
"sg",
"=",
"NSServiceGroup",
"(",
")",
"sg"... | Returns a list of members of a servicegroup or None | [
"Returns",
"a",
"list",
"of",
"members",
"of",
"a",
"servicegroup",
"or",
"None"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L162-L177 | train |
saltstack/salt | salt/modules/netscaler.py | _servicegroup_get_server | def _servicegroup_get_server(sg_name, s_name, s_port=None, **connection_args):
'''
Returns a member of a service group or None
'''
ret = None
servers = _servicegroup_get_servers(sg_name, **connection_args)
if servers is None:
return None
for server in servers:
if server.get_servername() == s_name:
if s_port is not None and s_port != server.get_port():
ret = None
ret = server
return ret | python | def _servicegroup_get_server(sg_name, s_name, s_port=None, **connection_args):
'''
Returns a member of a service group or None
'''
ret = None
servers = _servicegroup_get_servers(sg_name, **connection_args)
if servers is None:
return None
for server in servers:
if server.get_servername() == s_name:
if s_port is not None and s_port != server.get_port():
ret = None
ret = server
return ret | [
"def",
"_servicegroup_get_server",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"None",
"servers",
"=",
"_servicegroup_get_servers",
"(",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
... | Returns a member of a service group or None | [
"Returns",
"a",
"member",
"of",
"a",
"service",
"group",
"or",
"None"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L180-L193 | train |
saltstack/salt | salt/modules/netscaler.py | servicegroup_exists | def servicegroup_exists(sg_name, sg_type=None, **connection_args):
'''
Checks if a service group exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_exists 'serviceGroupName'
'''
sg = _servicegroup_get(sg_name, **connection_args)
if sg is None:
return False
if sg_type is not None and sg_type.upper() != sg.get_servicetype():
return False
return True | python | def servicegroup_exists(sg_name, sg_type=None, **connection_args):
'''
Checks if a service group exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_exists 'serviceGroupName'
'''
sg = _servicegroup_get(sg_name, **connection_args)
if sg is None:
return False
if sg_type is not None and sg_type.upper() != sg.get_servicetype():
return False
return True | [
"def",
"servicegroup_exists",
"(",
"sg_name",
",",
"sg_type",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"sg",
"=",
"_servicegroup_get",
"(",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"sg",
"is",
"None",
":",
"return",
"False",
... | Checks if a service group exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_exists 'serviceGroupName' | [
"Checks",
"if",
"a",
"service",
"group",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L196-L211 | train |
saltstack/salt | salt/modules/netscaler.py | servicegroup_add | def servicegroup_add(sg_name, sg_type='HTTP', **connection_args):
'''
Add a new service group
If no service type is specified, HTTP will be used.
Most common service types: HTTP, SSL, and SSL_BRIDGE
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_add 'serviceGroupName'
salt '*' netscaler.servicegroup_add 'serviceGroupName' 'serviceGroupType'
'''
ret = True
if servicegroup_exists(sg_name):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
sg = NSServiceGroup()
sg.set_servicegroupname(sg_name)
sg.set_servicetype(sg_type.upper())
try:
NSServiceGroup.add(nitro, sg)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def servicegroup_add(sg_name, sg_type='HTTP', **connection_args):
'''
Add a new service group
If no service type is specified, HTTP will be used.
Most common service types: HTTP, SSL, and SSL_BRIDGE
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_add 'serviceGroupName'
salt '*' netscaler.servicegroup_add 'serviceGroupName' 'serviceGroupType'
'''
ret = True
if servicegroup_exists(sg_name):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
sg = NSServiceGroup()
sg.set_servicegroupname(sg_name)
sg.set_servicetype(sg_type.upper())
try:
NSServiceGroup.add(nitro, sg)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"servicegroup_add",
"(",
"sg_name",
",",
"sg_type",
"=",
"'HTTP'",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"if",
"servicegroup_exists",
"(",
"sg_name",
")",
":",
"return",
"False",
"nitro",
"=",
"_connect",
"(",
"*",
"*",
"... | Add a new service group
If no service type is specified, HTTP will be used.
Most common service types: HTTP, SSL, and SSL_BRIDGE
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_add 'serviceGroupName'
salt '*' netscaler.servicegroup_add 'serviceGroupName' 'serviceGroupType' | [
"Add",
"a",
"new",
"service",
"group",
"If",
"no",
"service",
"type",
"is",
"specified",
"HTTP",
"will",
"be",
"used",
".",
"Most",
"common",
"service",
"types",
":",
"HTTP",
"SSL",
"and",
"SSL_BRIDGE"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L214-L242 | train |
saltstack/salt | salt/modules/netscaler.py | servicegroup_delete | def servicegroup_delete(sg_name, **connection_args):
'''
Delete a new service group
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_delete 'serviceGroupName'
'''
ret = True
sg = _servicegroup_get(sg_name, **connection_args)
if sg is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSServiceGroup.delete(nitro, sg)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.delete() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def servicegroup_delete(sg_name, **connection_args):
'''
Delete a new service group
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_delete 'serviceGroupName'
'''
ret = True
sg = _servicegroup_get(sg_name, **connection_args)
if sg is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSServiceGroup.delete(nitro, sg)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.delete() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"servicegroup_delete",
"(",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"sg",
"=",
"_servicegroup_get",
"(",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"sg",
"is",
"None",
":",
"return",
"False",
"nitro",
... | Delete a new service group
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_delete 'serviceGroupName' | [
"Delete",
"a",
"new",
"service",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L245-L268 | train |
saltstack/salt | salt/modules/netscaler.py | servicegroup_server_exists | def servicegroup_server_exists(sg_name, s_name, s_port=None, **connection_args):
'''
Check if a server:port combination is a member of a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_exists 'serviceGroupName' 'serverName' 'serverPort'
'''
return _servicegroup_get_server(sg_name, s_name, s_port, **connection_args) is not None | python | def servicegroup_server_exists(sg_name, s_name, s_port=None, **connection_args):
'''
Check if a server:port combination is a member of a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_exists 'serviceGroupName' 'serverName' 'serverPort'
'''
return _servicegroup_get_server(sg_name, s_name, s_port, **connection_args) is not None | [
"def",
"servicegroup_server_exists",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"return",
"_servicegroup_get_server",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
",",
"*",
"*",
"connection_args",
")... | Check if a server:port combination is a member of a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_exists 'serviceGroupName' 'serverName' 'serverPort' | [
"Check",
"if",
"a",
"server",
":",
"port",
"combination",
"is",
"a",
"member",
"of",
"a",
"servicegroup"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L271-L281 | train |
saltstack/salt | salt/modules/netscaler.py | servicegroup_server_up | def servicegroup_server_up(sg_name, s_name, s_port, **connection_args):
'''
Check if a server:port combination is in state UP in a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_up 'serviceGroupName' 'serverName' 'serverPort'
'''
server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args)
return server is not None and server.get_svrstate() == 'UP' | python | def servicegroup_server_up(sg_name, s_name, s_port, **connection_args):
'''
Check if a server:port combination is in state UP in a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_up 'serviceGroupName' 'serverName' 'serverPort'
'''
server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args)
return server is not None and server.get_svrstate() == 'UP' | [
"def",
"servicegroup_server_up",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
",",
"*",
"*",
"connection_args",
")",
":",
"server",
"=",
"_servicegroup_get_server",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
",",
"*",
"*",
"connection_args",
")",
"return",... | Check if a server:port combination is in state UP in a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_up 'serviceGroupName' 'serverName' 'serverPort' | [
"Check",
"if",
"a",
"server",
":",
"port",
"combination",
"is",
"in",
"state",
"UP",
"in",
"a",
"servicegroup"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L284-L295 | train |
saltstack/salt | salt/modules/netscaler.py | servicegroup_server_enable | def servicegroup_server_enable(sg_name, s_name, s_port, **connection_args):
'''
Enable a server:port member of a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_enable 'serviceGroupName' 'serverName' 'serverPort'
'''
ret = True
server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args)
if server is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSServiceGroup.enable_server(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.enable_server() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def servicegroup_server_enable(sg_name, s_name, s_port, **connection_args):
'''
Enable a server:port member of a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_enable 'serviceGroupName' 'serverName' 'serverPort'
'''
ret = True
server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args)
if server is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSServiceGroup.enable_server(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.enable_server() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"servicegroup_server_enable",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"server",
"=",
"_servicegroup_get_server",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
",",
"*",
"*",
"connec... | Enable a server:port member of a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_enable 'serviceGroupName' 'serverName' 'serverPort' | [
"Enable",
"a",
"server",
":",
"port",
"member",
"of",
"a",
"servicegroup"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L298-L321 | train |
saltstack/salt | salt/modules/netscaler.py | servicegroup_server_add | def servicegroup_server_add(sg_name, s_name, s_port, **connection_args):
'''
Add a server:port member to a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_add 'serviceGroupName' 'serverName' 'serverPort'
'''
# Nitro will throw an error if the server is already present
ret = True
server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args)
if server is not None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
sgsb = NSServiceGroupServerBinding()
sgsb.set_servicegroupname(sg_name)
sgsb.set_servername(s_name)
sgsb.set_port(s_port)
try:
NSServiceGroupServerBinding.add(nitro, sgsb)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroupServerBinding() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def servicegroup_server_add(sg_name, s_name, s_port, **connection_args):
'''
Add a server:port member to a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_add 'serviceGroupName' 'serverName' 'serverPort'
'''
# Nitro will throw an error if the server is already present
ret = True
server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args)
if server is not None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
sgsb = NSServiceGroupServerBinding()
sgsb.set_servicegroupname(sg_name)
sgsb.set_servername(s_name)
sgsb.set_port(s_port)
try:
NSServiceGroupServerBinding.add(nitro, sgsb)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroupServerBinding() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"servicegroup_server_add",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
",",
"*",
"*",
"connection_args",
")",
":",
"# Nitro will throw an error if the server is already present",
"ret",
"=",
"True",
"server",
"=",
"_servicegroup_get_server",
"(",
"sg_name",
","... | Add a server:port member to a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_add 'serviceGroupName' 'serverName' 'serverPort' | [
"Add",
"a",
"server",
":",
"port",
"member",
"to",
"a",
"servicegroup"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L350-L378 | train |
saltstack/salt | salt/modules/netscaler.py | _service_get | def _service_get(s_name, **connection_args):
'''
Returns a service ressource or None
'''
nitro = _connect(**connection_args)
if nitro is None:
return None
service = NSService()
service.set_name(s_name)
try:
service = NSService.get(nitro, service)
except NSNitroError as error:
log.debug('netscaler module error - NSService.get() failed: %s', error)
service = None
_disconnect(nitro)
return service | python | def _service_get(s_name, **connection_args):
'''
Returns a service ressource or None
'''
nitro = _connect(**connection_args)
if nitro is None:
return None
service = NSService()
service.set_name(s_name)
try:
service = NSService.get(nitro, service)
except NSNitroError as error:
log.debug('netscaler module error - NSService.get() failed: %s', error)
service = None
_disconnect(nitro)
return service | [
"def",
"_service_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
":",
"nitro",
"=",
"_connect",
"(",
"*",
"*",
"connection_args",
")",
"if",
"nitro",
"is",
"None",
":",
"return",
"None",
"service",
"=",
"NSService",
"(",
")",
"service",
".",
... | Returns a service ressource or None | [
"Returns",
"a",
"service",
"ressource",
"or",
"None"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L412-L427 | train |
saltstack/salt | salt/modules/netscaler.py | service_up | def service_up(s_name, **connection_args):
'''
Checks if a service is UP
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_up 'serviceName'
'''
service = _service_get(s_name, **connection_args)
return service is not None and service.get_svrstate() == 'UP' | python | def service_up(s_name, **connection_args):
'''
Checks if a service is UP
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_up 'serviceName'
'''
service = _service_get(s_name, **connection_args)
return service is not None and service.get_svrstate() == 'UP' | [
"def",
"service_up",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
":",
"service",
"=",
"_service_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
"return",
"service",
"is",
"not",
"None",
"and",
"service",
".",
"get_svrstate",
"(",
")",... | Checks if a service is UP
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_up 'serviceName' | [
"Checks",
"if",
"a",
"service",
"is",
"UP"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L443-L454 | train |
saltstack/salt | salt/modules/netscaler.py | service_enable | def service_enable(s_name, **connection_args):
'''
Enable a service
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_enable 'serviceName'
'''
ret = True
service = _service_get(s_name, **connection_args)
if service is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSService.enable(nitro, service)
except NSNitroError as error:
log.debug('netscaler module error - NSService.enable() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def service_enable(s_name, **connection_args):
'''
Enable a service
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_enable 'serviceName'
'''
ret = True
service = _service_get(s_name, **connection_args)
if service is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSService.enable(nitro, service)
except NSNitroError as error:
log.debug('netscaler module error - NSService.enable() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"service_enable",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"service",
"=",
"_service_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"service",
"is",
"None",
":",
"return",
"False",
"nitro",
... | Enable a service
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_enable 'serviceName' | [
"Enable",
"a",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L457-L481 | train |
saltstack/salt | salt/modules/netscaler.py | service_disable | def service_disable(s_name, s_delay=None, **connection_args):
'''
Disable a service
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_disable 'serviceName'
salt '*' netscaler.service_disable 'serviceName' 'delayInSeconds'
'''
ret = True
service = _service_get(s_name, **connection_args)
if service is None:
return False
if s_delay is not None:
service.set_delay(s_delay)
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSService.disable(nitro, service)
except NSNitroError as error:
log.debug('netscaler module error - NSService.enable() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def service_disable(s_name, s_delay=None, **connection_args):
'''
Disable a service
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_disable 'serviceName'
salt '*' netscaler.service_disable 'serviceName' 'delayInSeconds'
'''
ret = True
service = _service_get(s_name, **connection_args)
if service is None:
return False
if s_delay is not None:
service.set_delay(s_delay)
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSService.disable(nitro, service)
except NSNitroError as error:
log.debug('netscaler module error - NSService.enable() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"service_disable",
"(",
"s_name",
",",
"s_delay",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"service",
"=",
"_service_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"service",
"is",
"None",
":"... | Disable a service
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_disable 'serviceName'
salt '*' netscaler.service_disable 'serviceName' 'delayInSeconds' | [
"Disable",
"a",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L484-L510 | train |
saltstack/salt | salt/modules/netscaler.py | server_exists | def server_exists(s_name, ip=None, s_state=None, **connection_args):
'''
Checks if a server exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_exists 'serverName'
'''
server = _server_get(s_name, **connection_args)
if server is None:
return False
if ip is not None and ip != server.get_ipaddress():
return False
if s_state is not None and s_state.upper() != server.get_state():
return False
return True | python | def server_exists(s_name, ip=None, s_state=None, **connection_args):
'''
Checks if a server exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_exists 'serverName'
'''
server = _server_get(s_name, **connection_args)
if server is None:
return False
if ip is not None and ip != server.get_ipaddress():
return False
if s_state is not None and s_state.upper() != server.get_state():
return False
return True | [
"def",
"server_exists",
"(",
"s_name",
",",
"ip",
"=",
"None",
",",
"s_state",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"server",
"=",
"_server_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"server",
"is",
"None",
":... | Checks if a server exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_exists 'serverName' | [
"Checks",
"if",
"a",
"server",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L528-L545 | train |
saltstack/salt | salt/modules/netscaler.py | server_add | def server_add(s_name, s_ip, s_state=None, **connection_args):
'''
Add a server
Note: The default server state is ENABLED
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_add 'serverName' 'serverIpAddress'
salt '*' netscaler.server_add 'serverName' 'serverIpAddress' 'serverState'
'''
ret = True
if server_exists(s_name, **connection_args):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
server = NSServer()
server.set_name(s_name)
server.set_ipaddress(s_ip)
if s_state is not None:
server.set_state(s_state)
try:
NSServer.add(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServer.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def server_add(s_name, s_ip, s_state=None, **connection_args):
'''
Add a server
Note: The default server state is ENABLED
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_add 'serverName' 'serverIpAddress'
salt '*' netscaler.server_add 'serverName' 'serverIpAddress' 'serverState'
'''
ret = True
if server_exists(s_name, **connection_args):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
server = NSServer()
server.set_name(s_name)
server.set_ipaddress(s_ip)
if s_state is not None:
server.set_state(s_state)
try:
NSServer.add(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServer.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"server_add",
"(",
"s_name",
",",
"s_ip",
",",
"s_state",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"if",
"server_exists",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
":",
"return",
"False",
"nitro",
... | Add a server
Note: The default server state is ENABLED
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_add 'serverName' 'serverIpAddress'
salt '*' netscaler.server_add 'serverName' 'serverIpAddress' 'serverState' | [
"Add",
"a",
"server",
"Note",
":",
"The",
"default",
"server",
"state",
"is",
"ENABLED"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L548-L577 | train |
saltstack/salt | salt/modules/netscaler.py | server_delete | def server_delete(s_name, **connection_args):
'''
Delete a server
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_delete 'serverName'
'''
ret = True
server = _server_get(s_name, **connection_args)
if server is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSServer.delete(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServer.delete() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def server_delete(s_name, **connection_args):
'''
Delete a server
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_delete 'serverName'
'''
ret = True
server = _server_get(s_name, **connection_args)
if server is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSServer.delete(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServer.delete() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"server_delete",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"server",
"=",
"_server_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"server",
"is",
"None",
":",
"return",
"False",
"nitro",
"=",... | Delete a server
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_delete 'serverName' | [
"Delete",
"a",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L580-L603 | train |
saltstack/salt | salt/modules/netscaler.py | server_update | def server_update(s_name, s_ip, **connection_args):
'''
Update a server's attributes
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_update 'serverName' 'serverIP'
'''
altered = False
cur_server = _server_get(s_name, **connection_args)
if cur_server is None:
return False
alt_server = NSServer()
alt_server.set_name(s_name)
if cur_server.get_ipaddress() != s_ip:
alt_server.set_ipaddress(s_ip)
altered = True
# Nothing to update, the server is already idem
if altered is False:
return False
# Perform the update
nitro = _connect(**connection_args)
if nitro is None:
return False
ret = True
try:
NSServer.update(nitro, alt_server)
except NSNitroError as error:
log.debug('netscaler module error - NSServer.update() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def server_update(s_name, s_ip, **connection_args):
'''
Update a server's attributes
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_update 'serverName' 'serverIP'
'''
altered = False
cur_server = _server_get(s_name, **connection_args)
if cur_server is None:
return False
alt_server = NSServer()
alt_server.set_name(s_name)
if cur_server.get_ipaddress() != s_ip:
alt_server.set_ipaddress(s_ip)
altered = True
# Nothing to update, the server is already idem
if altered is False:
return False
# Perform the update
nitro = _connect(**connection_args)
if nitro is None:
return False
ret = True
try:
NSServer.update(nitro, alt_server)
except NSNitroError as error:
log.debug('netscaler module error - NSServer.update() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"server_update",
"(",
"s_name",
",",
"s_ip",
",",
"*",
"*",
"connection_args",
")",
":",
"altered",
"=",
"False",
"cur_server",
"=",
"_server_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"cur_server",
"is",
"None",
":",
"return"... | Update a server's attributes
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_update 'serverName' 'serverIP' | [
"Update",
"a",
"server",
"s",
"attributes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L606-L639 | train |
saltstack/salt | salt/modules/netscaler.py | server_enabled | def server_enabled(s_name, **connection_args):
'''
Check if a server is enabled globally
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_enabled 'serverName'
'''
server = _server_get(s_name, **connection_args)
return server is not None and server.get_state() == 'ENABLED' | python | def server_enabled(s_name, **connection_args):
'''
Check if a server is enabled globally
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_enabled 'serverName'
'''
server = _server_get(s_name, **connection_args)
return server is not None and server.get_state() == 'ENABLED' | [
"def",
"server_enabled",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
":",
"server",
"=",
"_server_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
"return",
"server",
"is",
"not",
"None",
"and",
"server",
".",
"get_state",
"(",
")",
... | Check if a server is enabled globally
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_enabled 'serverName' | [
"Check",
"if",
"a",
"server",
"is",
"enabled",
"globally"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L642-L653 | train |
saltstack/salt | salt/modules/netscaler.py | server_enable | def server_enable(s_name, **connection_args):
'''
Enables a server globally
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_enable 'serverName'
'''
ret = True
server = _server_get(s_name, **connection_args)
if server is None:
return False
if server.get_state() == 'ENABLED':
return True
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSServer.enable(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServer.enable() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def server_enable(s_name, **connection_args):
'''
Enables a server globally
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_enable 'serverName'
'''
ret = True
server = _server_get(s_name, **connection_args)
if server is None:
return False
if server.get_state() == 'ENABLED':
return True
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSServer.enable(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServer.enable() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"server_enable",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"server",
"=",
"_server_get",
"(",
"s_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"server",
"is",
"None",
":",
"return",
"False",
"if",
"server... | Enables a server globally
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_enable 'serverName' | [
"Enables",
"a",
"server",
"globally"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L656-L681 | train |
saltstack/salt | salt/modules/netscaler.py | vserver_exists | def vserver_exists(v_name, v_ip=None, v_port=None, v_type=None, **connection_args):
'''
Checks if a vserver exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_exists 'vserverName'
'''
vserver = _vserver_get(v_name, **connection_args)
if vserver is None:
return False
if v_ip is not None and vserver.get_ipv46() != v_ip:
return False
if v_port is not None and vserver.get_port() != v_port:
return False
if v_type is not None and vserver.get_servicetype().upper() != v_type.upper():
return False
return True | python | def vserver_exists(v_name, v_ip=None, v_port=None, v_type=None, **connection_args):
'''
Checks if a vserver exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_exists 'vserverName'
'''
vserver = _vserver_get(v_name, **connection_args)
if vserver is None:
return False
if v_ip is not None and vserver.get_ipv46() != v_ip:
return False
if v_port is not None and vserver.get_port() != v_port:
return False
if v_type is not None and vserver.get_servicetype().upper() != v_type.upper():
return False
return True | [
"def",
"vserver_exists",
"(",
"v_name",
",",
"v_ip",
"=",
"None",
",",
"v_port",
"=",
"None",
",",
"v_type",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"vserver",
"=",
"_vserver_get",
"(",
"v_name",
",",
"*",
"*",
"connection_args",
")",
... | Checks if a vserver exists
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_exists 'vserverName' | [
"Checks",
"if",
"a",
"vserver",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L727-L746 | train |
saltstack/salt | salt/modules/netscaler.py | vserver_add | def vserver_add(v_name, v_ip, v_port, v_type, **connection_args):
'''
Add a new lb vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_add 'vserverName' 'vserverIP' 'vserverPort' 'vserverType'
salt '*' netscaler.vserver_add 'alex.patate.chaude.443' '1.2.3.4' '443' 'SSL'
'''
ret = True
if vserver_exists(v_name, **connection_args):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
vserver = NSLBVServer()
vserver.set_name(v_name)
vserver.set_ipv46(v_ip)
vserver.set_port(v_port)
vserver.set_servicetype(v_type.upper())
try:
NSLBVServer.add(nitro, vserver)
except NSNitroError as error:
log.debug('netscaler module error - NSLBVServer.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def vserver_add(v_name, v_ip, v_port, v_type, **connection_args):
'''
Add a new lb vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_add 'vserverName' 'vserverIP' 'vserverPort' 'vserverType'
salt '*' netscaler.vserver_add 'alex.patate.chaude.443' '1.2.3.4' '443' 'SSL'
'''
ret = True
if vserver_exists(v_name, **connection_args):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
vserver = NSLBVServer()
vserver.set_name(v_name)
vserver.set_ipv46(v_ip)
vserver.set_port(v_port)
vserver.set_servicetype(v_type.upper())
try:
NSLBVServer.add(nitro, vserver)
except NSNitroError as error:
log.debug('netscaler module error - NSLBVServer.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"vserver_add",
"(",
"v_name",
",",
"v_ip",
",",
"v_port",
",",
"v_type",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"if",
"vserver_exists",
"(",
"v_name",
",",
"*",
"*",
"connection_args",
")",
":",
"return",
"False",
"nitro",... | Add a new lb vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_add 'vserverName' 'vserverIP' 'vserverPort' 'vserverType'
salt '*' netscaler.vserver_add 'alex.patate.chaude.443' '1.2.3.4' '443' 'SSL' | [
"Add",
"a",
"new",
"lb",
"vserver"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L749-L777 | train |
saltstack/salt | salt/modules/netscaler.py | vserver_delete | def vserver_delete(v_name, **connection_args):
'''
Delete a lb vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_delete 'vserverName'
'''
ret = True
vserver = _vserver_get(v_name, **connection_args)
if vserver is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSLBVServer.delete(nitro, vserver)
except NSNitroError as error:
log.debug('netscaler module error - NSVServer.delete() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def vserver_delete(v_name, **connection_args):
'''
Delete a lb vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_delete 'vserverName'
'''
ret = True
vserver = _vserver_get(v_name, **connection_args)
if vserver is None:
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
try:
NSLBVServer.delete(nitro, vserver)
except NSNitroError as error:
log.debug('netscaler module error - NSVServer.delete() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"vserver_delete",
"(",
"v_name",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"vserver",
"=",
"_vserver_get",
"(",
"v_name",
",",
"*",
"*",
"connection_args",
")",
"if",
"vserver",
"is",
"None",
":",
"return",
"False",
"nitro",
... | Delete a lb vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_delete 'vserverName' | [
"Delete",
"a",
"lb",
"vserver"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L780-L803 | train |
saltstack/salt | salt/modules/netscaler.py | vserver_servicegroup_add | def vserver_servicegroup_add(v_name, sg_name, **connection_args):
'''
Bind a servicegroup to a vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_servicegroup_add 'vserverName' 'serviceGroupName'
'''
ret = True
if vserver_servicegroup_exists(v_name, sg_name, **connection_args):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
vsg = NSLBVServerServiceGroupBinding()
vsg.set_name(v_name)
vsg.set_servicegroupname(sg_name)
try:
NSLBVServerServiceGroupBinding.add(nitro, vsg)
except NSNitroError as error:
log.debug('netscaler module error - NSLBVServerServiceGroupBinding.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def vserver_servicegroup_add(v_name, sg_name, **connection_args):
'''
Bind a servicegroup to a vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_servicegroup_add 'vserverName' 'serviceGroupName'
'''
ret = True
if vserver_servicegroup_exists(v_name, sg_name, **connection_args):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
vsg = NSLBVServerServiceGroupBinding()
vsg.set_name(v_name)
vsg.set_servicegroupname(sg_name)
try:
NSLBVServerServiceGroupBinding.add(nitro, vsg)
except NSNitroError as error:
log.debug('netscaler module error - NSLBVServerServiceGroupBinding.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"vserver_servicegroup_add",
"(",
"v_name",
",",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"if",
"vserver_servicegroup_exists",
"(",
"v_name",
",",
"sg_name",
",",
"*",
"*",
"connection_args",
")",
":",
"return",
"False",... | Bind a servicegroup to a vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_servicegroup_add 'vserverName' 'serviceGroupName' | [
"Bind",
"a",
"servicegroup",
"to",
"a",
"vserver"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L838-L863 | train |
saltstack/salt | salt/modules/netscaler.py | vserver_sslcert_add | def vserver_sslcert_add(v_name, sc_name, **connection_args):
'''
Binds a SSL certificate to a vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_sslcert_add 'vserverName' 'sslCertificateName'
'''
ret = True
if vserver_sslcert_exists(v_name, sc_name, **connection_args):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
sslcert = NSSSLVServerSSLCertKeyBinding()
sslcert.set_vservername(v_name)
sslcert.set_certkeyname(sc_name)
try:
NSSSLVServerSSLCertKeyBinding.add(nitro, sslcert)
except NSNitroError as error:
log.debug('netscaler module error - NSSSLVServerSSLCertKeyBinding.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | python | def vserver_sslcert_add(v_name, sc_name, **connection_args):
'''
Binds a SSL certificate to a vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_sslcert_add 'vserverName' 'sslCertificateName'
'''
ret = True
if vserver_sslcert_exists(v_name, sc_name, **connection_args):
return False
nitro = _connect(**connection_args)
if nitro is None:
return False
sslcert = NSSSLVServerSSLCertKeyBinding()
sslcert.set_vservername(v_name)
sslcert.set_certkeyname(sc_name)
try:
NSSSLVServerSSLCertKeyBinding.add(nitro, sslcert)
except NSNitroError as error:
log.debug('netscaler module error - NSSSLVServerSSLCertKeyBinding.add() failed: %s', error)
ret = False
_disconnect(nitro)
return ret | [
"def",
"vserver_sslcert_add",
"(",
"v_name",
",",
"sc_name",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"True",
"if",
"vserver_sslcert_exists",
"(",
"v_name",
",",
"sc_name",
",",
"*",
"*",
"connection_args",
")",
":",
"return",
"False",
"nitro"... | Binds a SSL certificate to a vserver
CLI Example:
.. code-block:: bash
salt '*' netscaler.vserver_sslcert_add 'vserverName' 'sslCertificateName' | [
"Binds",
"a",
"SSL",
"certificate",
"to",
"a",
"vserver"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netscaler.py#L925-L950 | train |
saltstack/salt | salt/modules/libcloud_dns.py | list_zones | def list_zones(profile):
'''
List zones for the given profile
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.list_zones profile1
'''
conn = _get_driver(profile=profile)
return [_simple_zone(zone) for zone in conn.list_zones()] | python | def list_zones(profile):
'''
List zones for the given profile
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.list_zones profile1
'''
conn = _get_driver(profile=profile)
return [_simple_zone(zone) for zone in conn.list_zones()] | [
"def",
"list_zones",
"(",
"profile",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"return",
"[",
"_simple_zone",
"(",
"zone",
")",
"for",
"zone",
"in",
"conn",
".",
"list_zones",
"(",
")",
"]"
] | List zones for the given profile
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.list_zones profile1 | [
"List",
"zones",
"for",
"the",
"given",
"profile"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L103-L117 | train |
saltstack/salt | salt/modules/libcloud_dns.py | list_records | def list_records(zone_id, profile, type=None):
'''
List records for the given zone_id on the given profile
:param zone_id: Zone to export.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: The record type, e.g. A, NS
:type type: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.list_records google.com profile1
'''
conn = _get_driver(profile=profile)
zone = conn.get_zone(zone_id)
if type is not None:
return [_simple_record(record) for record in conn.list_records(zone) if record.type == type]
else:
return [_simple_record(record) for record in conn.list_records(zone)] | python | def list_records(zone_id, profile, type=None):
'''
List records for the given zone_id on the given profile
:param zone_id: Zone to export.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: The record type, e.g. A, NS
:type type: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.list_records google.com profile1
'''
conn = _get_driver(profile=profile)
zone = conn.get_zone(zone_id)
if type is not None:
return [_simple_record(record) for record in conn.list_records(zone) if record.type == type]
else:
return [_simple_record(record) for record in conn.list_records(zone)] | [
"def",
"list_records",
"(",
"zone_id",
",",
"profile",
",",
"type",
"=",
"None",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"zone",
"=",
"conn",
".",
"get_zone",
"(",
"zone_id",
")",
"if",
"type",
"is",
"not",
"None",
... | List records for the given zone_id on the given profile
:param zone_id: Zone to export.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: The record type, e.g. A, NS
:type type: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.list_records google.com profile1 | [
"List",
"records",
"for",
"the",
"given",
"zone_id",
"on",
"the",
"given",
"profile"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L120-L144 | train |
saltstack/salt | salt/modules/libcloud_dns.py | get_zone | def get_zone(zone_id, profile):
'''
Get zone information for the given zone_id on the given profile
:param zone_id: Zone to export.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.get_zone google.com profile1
'''
conn = _get_driver(profile=profile)
return _simple_zone(conn.get_zone(zone_id)) | python | def get_zone(zone_id, profile):
'''
Get zone information for the given zone_id on the given profile
:param zone_id: Zone to export.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.get_zone google.com profile1
'''
conn = _get_driver(profile=profile)
return _simple_zone(conn.get_zone(zone_id)) | [
"def",
"get_zone",
"(",
"zone_id",
",",
"profile",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"return",
"_simple_zone",
"(",
"conn",
".",
"get_zone",
"(",
"zone_id",
")",
")"
] | Get zone information for the given zone_id on the given profile
:param zone_id: Zone to export.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.get_zone google.com profile1 | [
"Get",
"zone",
"information",
"for",
"the",
"given",
"zone_id",
"on",
"the",
"given",
"profile"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L147-L164 | train |
saltstack/salt | salt/modules/libcloud_dns.py | get_record | def get_record(zone_id, record_id, profile):
'''
Get record information for the given zone_id on the given profile
:param zone_id: Zone to export.
:type zone_id: ``str``
:param record_id: Record to delete.
:type record_id: ``str``
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.get_record google.com www profile1
'''
conn = _get_driver(profile=profile)
return _simple_record(conn.get_record(zone_id, record_id)) | python | def get_record(zone_id, record_id, profile):
'''
Get record information for the given zone_id on the given profile
:param zone_id: Zone to export.
:type zone_id: ``str``
:param record_id: Record to delete.
:type record_id: ``str``
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.get_record google.com www profile1
'''
conn = _get_driver(profile=profile)
return _simple_record(conn.get_record(zone_id, record_id)) | [
"def",
"get_record",
"(",
"zone_id",
",",
"record_id",
",",
"profile",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"return",
"_simple_record",
"(",
"conn",
".",
"get_record",
"(",
"zone_id",
",",
"record_id",
")",
")"
] | Get record information for the given zone_id on the given profile
:param zone_id: Zone to export.
:type zone_id: ``str``
:param record_id: Record to delete.
:type record_id: ``str``
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.get_record google.com www profile1 | [
"Get",
"record",
"information",
"for",
"the",
"given",
"zone_id",
"on",
"the",
"given",
"profile"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L167-L187 | train |
saltstack/salt | salt/modules/libcloud_dns.py | create_zone | def create_zone(domain, profile, type='master', ttl=None):
'''
Create a new zone.
:param domain: Zone domain name (e.g. example.com)
:type domain: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: Zone type (master / slave).
:type type: ``str``
:param ttl: TTL for new records. (optional)
:type ttl: ``int``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.create_zone google.com profile1
'''
conn = _get_driver(profile=profile)
zone = conn.create_record(domain, type=type, ttl=ttl)
return _simple_zone(zone) | python | def create_zone(domain, profile, type='master', ttl=None):
'''
Create a new zone.
:param domain: Zone domain name (e.g. example.com)
:type domain: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: Zone type (master / slave).
:type type: ``str``
:param ttl: TTL for new records. (optional)
:type ttl: ``int``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.create_zone google.com profile1
'''
conn = _get_driver(profile=profile)
zone = conn.create_record(domain, type=type, ttl=ttl)
return _simple_zone(zone) | [
"def",
"create_zone",
"(",
"domain",
",",
"profile",
",",
"type",
"=",
"'master'",
",",
"ttl",
"=",
"None",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"zone",
"=",
"conn",
".",
"create_record",
"(",
"domain",
",",
"type"... | Create a new zone.
:param domain: Zone domain name (e.g. example.com)
:type domain: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: Zone type (master / slave).
:type type: ``str``
:param ttl: TTL for new records. (optional)
:type ttl: ``int``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.create_zone google.com profile1 | [
"Create",
"a",
"new",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L190-L214 | train |
saltstack/salt | salt/modules/libcloud_dns.py | update_zone | def update_zone(zone_id, domain, profile, type='master', ttl=None):
'''
Update an existing zone.
:param zone_id: Zone ID to update.
:type zone_id: ``str``
:param domain: Zone domain name (e.g. example.com)
:type domain: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: Zone type (master / slave).
:type type: ``str``
:param ttl: TTL for new records. (optional)
:type ttl: ``int``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.update_zone google.com google.com profile1 type=slave
'''
conn = _get_driver(profile=profile)
zone = conn.get_zone(zone_id)
return _simple_zone(conn.update_zone(zone=zone, domain=domain, type=type, ttl=ttl)) | python | def update_zone(zone_id, domain, profile, type='master', ttl=None):
'''
Update an existing zone.
:param zone_id: Zone ID to update.
:type zone_id: ``str``
:param domain: Zone domain name (e.g. example.com)
:type domain: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: Zone type (master / slave).
:type type: ``str``
:param ttl: TTL for new records. (optional)
:type ttl: ``int``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.update_zone google.com google.com profile1 type=slave
'''
conn = _get_driver(profile=profile)
zone = conn.get_zone(zone_id)
return _simple_zone(conn.update_zone(zone=zone, domain=domain, type=type, ttl=ttl)) | [
"def",
"update_zone",
"(",
"zone_id",
",",
"domain",
",",
"profile",
",",
"type",
"=",
"'master'",
",",
"ttl",
"=",
"None",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"zone",
"=",
"conn",
".",
"get_zone",
"(",
"zone_id",... | Update an existing zone.
:param zone_id: Zone ID to update.
:type zone_id: ``str``
:param domain: Zone domain name (e.g. example.com)
:type domain: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: Zone type (master / slave).
:type type: ``str``
:param ttl: TTL for new records. (optional)
:type ttl: ``int``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.update_zone google.com google.com profile1 type=slave | [
"Update",
"an",
"existing",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L217-L244 | train |
saltstack/salt | salt/modules/libcloud_dns.py | create_record | def create_record(name, zone_id, type, data, profile):
'''
Create a new record.
:param name: Record name without the domain name (e.g. www).
Note: If you want to create a record for a base domain
name, you should specify empty string ('') for this
argument.
:type name: ``str``
:param zone_id: Zone where the requested record is created.
:type zone_id: ``str``
:param type: DNS record type (A, AAAA, ...).
:type type: ``str``
:param data: Data for the record (depends on the record type).
:type data: ``str``
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.create_record www google.com A 12.32.12.2 profile1
'''
conn = _get_driver(profile=profile)
record_type = _string_to_record_type(type)
zone = conn.get_zone(zone_id)
return _simple_record(conn.create_record(name, zone, record_type, data)) | python | def create_record(name, zone_id, type, data, profile):
'''
Create a new record.
:param name: Record name without the domain name (e.g. www).
Note: If you want to create a record for a base domain
name, you should specify empty string ('') for this
argument.
:type name: ``str``
:param zone_id: Zone where the requested record is created.
:type zone_id: ``str``
:param type: DNS record type (A, AAAA, ...).
:type type: ``str``
:param data: Data for the record (depends on the record type).
:type data: ``str``
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.create_record www google.com A 12.32.12.2 profile1
'''
conn = _get_driver(profile=profile)
record_type = _string_to_record_type(type)
zone = conn.get_zone(zone_id)
return _simple_record(conn.create_record(name, zone, record_type, data)) | [
"def",
"create_record",
"(",
"name",
",",
"zone_id",
",",
"type",
",",
"data",
",",
"profile",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"record_type",
"=",
"_string_to_record_type",
"(",
"type",
")",
"zone",
"=",
"conn",
... | Create a new record.
:param name: Record name without the domain name (e.g. www).
Note: If you want to create a record for a base domain
name, you should specify empty string ('') for this
argument.
:type name: ``str``
:param zone_id: Zone where the requested record is created.
:type zone_id: ``str``
:param type: DNS record type (A, AAAA, ...).
:type type: ``str``
:param data: Data for the record (depends on the record type).
:type data: ``str``
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.create_record www google.com A 12.32.12.2 profile1 | [
"Create",
"a",
"new",
"record",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L247-L278 | train |
saltstack/salt | salt/modules/libcloud_dns.py | delete_zone | def delete_zone(zone_id, profile):
'''
Delete a zone.
:param zone_id: Zone to delete.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
:rtype: ``bool``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.delete_zone google.com profile1
'''
conn = _get_driver(profile=profile)
zone = conn.get_zone(zone_id=zone_id)
return conn.delete_zone(zone) | python | def delete_zone(zone_id, profile):
'''
Delete a zone.
:param zone_id: Zone to delete.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
:rtype: ``bool``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.delete_zone google.com profile1
'''
conn = _get_driver(profile=profile)
zone = conn.get_zone(zone_id=zone_id)
return conn.delete_zone(zone) | [
"def",
"delete_zone",
"(",
"zone_id",
",",
"profile",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"zone",
"=",
"conn",
".",
"get_zone",
"(",
"zone_id",
"=",
"zone_id",
")",
"return",
"conn",
".",
"delete_zone",
"(",
"zone",... | Delete a zone.
:param zone_id: Zone to delete.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
:rtype: ``bool``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.delete_zone google.com profile1 | [
"Delete",
"a",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L281-L301 | train |
saltstack/salt | salt/modules/libcloud_dns.py | delete_record | def delete_record(zone_id, record_id, profile):
'''
Delete a record.
:param zone_id: Zone to delete.
:type zone_id: ``str``
:param record_id: Record to delete.
:type record_id: ``str``
:param profile: The profile key
:type profile: ``str``
:rtype: ``bool``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.delete_record google.com www profile1
'''
conn = _get_driver(profile=profile)
record = conn.get_record(zone_id=zone_id, record_id=record_id)
return conn.delete_record(record) | python | def delete_record(zone_id, record_id, profile):
'''
Delete a record.
:param zone_id: Zone to delete.
:type zone_id: ``str``
:param record_id: Record to delete.
:type record_id: ``str``
:param profile: The profile key
:type profile: ``str``
:rtype: ``bool``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.delete_record google.com www profile1
'''
conn = _get_driver(profile=profile)
record = conn.get_record(zone_id=zone_id, record_id=record_id)
return conn.delete_record(record) | [
"def",
"delete_record",
"(",
"zone_id",
",",
"record_id",
",",
"profile",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"record",
"=",
"conn",
".",
"get_record",
"(",
"zone_id",
"=",
"zone_id",
",",
"record_id",
"=",
"record_id... | Delete a record.
:param zone_id: Zone to delete.
:type zone_id: ``str``
:param record_id: Record to delete.
:type record_id: ``str``
:param profile: The profile key
:type profile: ``str``
:rtype: ``bool``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.delete_record google.com www profile1 | [
"Delete",
"a",
"record",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L304-L327 | train |
saltstack/salt | salt/modules/libcloud_dns.py | get_bind_data | def get_bind_data(zone_id, profile):
'''
Export Zone to the BIND compatible format.
:param zone_id: Zone to export.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
:return: Zone data in BIND compatible format.
:rtype: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.get_bind_data google.com profile1
'''
conn = _get_driver(profile=profile)
zone = conn.get_zone(zone_id)
return conn.export_zone_to_bind_format(zone) | python | def get_bind_data(zone_id, profile):
'''
Export Zone to the BIND compatible format.
:param zone_id: Zone to export.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
:return: Zone data in BIND compatible format.
:rtype: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.get_bind_data google.com profile1
'''
conn = _get_driver(profile=profile)
zone = conn.get_zone(zone_id)
return conn.export_zone_to_bind_format(zone) | [
"def",
"get_bind_data",
"(",
"zone_id",
",",
"profile",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"zone",
"=",
"conn",
".",
"get_zone",
"(",
"zone_id",
")",
"return",
"conn",
".",
"export_zone_to_bind_format",
"(",
"zone",
... | Export Zone to the BIND compatible format.
:param zone_id: Zone to export.
:type zone_id: ``str``
:param profile: The profile key
:type profile: ``str``
:return: Zone data in BIND compatible format.
:rtype: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.get_bind_data google.com profile1 | [
"Export",
"Zone",
"to",
"the",
"BIND",
"compatible",
"format",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L330-L351 | train |
saltstack/salt | salt/modules/libcloud_dns.py | extra | def extra(method, profile, **libcloud_kwargs):
'''
Call an extended method on the driver
:param method: Driver's method name
:type method: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's delete_container method
:type libcloud_kwargs: ``dict``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml
'''
_sanitize_kwargs(libcloud_kwargs)
conn = _get_driver(profile=profile)
connection_method = getattr(conn, method)
return connection_method(**libcloud_kwargs) | python | def extra(method, profile, **libcloud_kwargs):
'''
Call an extended method on the driver
:param method: Driver's method name
:type method: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's delete_container method
:type libcloud_kwargs: ``dict``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml
'''
_sanitize_kwargs(libcloud_kwargs)
conn = _get_driver(profile=profile)
connection_method = getattr(conn, method)
return connection_method(**libcloud_kwargs) | [
"def",
"extra",
"(",
"method",
",",
"profile",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"_sanitize_kwargs",
"(",
"libcloud_kwargs",
")",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"connection_method",
"=",
"getattr",
"(",
"conn",
","... | Call an extended method on the driver
:param method: Driver's method name
:type method: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's delete_container method
:type libcloud_kwargs: ``dict``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml | [
"Call",
"an",
"extended",
"method",
"on",
"the",
"driver"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L354-L376 | train |
saltstack/salt | salt/modules/libcloud_dns.py | _string_to_record_type | def _string_to_record_type(string):
'''
Return a string representation of a DNS record type to a
libcloud RecordType ENUM.
:param string: A record type, e.g. A, TXT, NS
:type string: ``str``
:rtype: :class:`RecordType`
'''
string = string.upper()
record_type = getattr(RecordType, string)
return record_type | python | def _string_to_record_type(string):
'''
Return a string representation of a DNS record type to a
libcloud RecordType ENUM.
:param string: A record type, e.g. A, TXT, NS
:type string: ``str``
:rtype: :class:`RecordType`
'''
string = string.upper()
record_type = getattr(RecordType, string)
return record_type | [
"def",
"_string_to_record_type",
"(",
"string",
")",
":",
"string",
"=",
"string",
".",
"upper",
"(",
")",
"record_type",
"=",
"getattr",
"(",
"RecordType",
",",
"string",
")",
"return",
"record_type"
] | Return a string representation of a DNS record type to a
libcloud RecordType ENUM.
:param string: A record type, e.g. A, TXT, NS
:type string: ``str``
:rtype: :class:`RecordType` | [
"Return",
"a",
"string",
"representation",
"of",
"a",
"DNS",
"record",
"type",
"to",
"a",
"libcloud",
"RecordType",
"ENUM",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L379-L391 | train |
saltstack/salt | salt/modules/ifttt.py | _query | def _query(event=None,
method='GET',
args=None,
header_dict=None,
data=None):
'''
Make a web call to IFTTT.
'''
secret_key = __salt__['config.get']('ifttt.secret_key') or \
__salt__['config.get']('ifttt:secret_key')
path = 'https://maker.ifttt.com/trigger/{0}/with/key/{1}'.format(event, secret_key)
if header_dict is None:
header_dict = {'Content-type': 'application/json'}
if method != 'POST':
header_dict['Accept'] = 'application/json'
result = salt.utils.http.query(
path,
method,
params={},
data=data,
header_dict=header_dict,
decode=True,
decode_type='auto',
text=True,
status=True,
cookies=True,
persist_session=True,
opts=__opts__,
backend='requests'
)
return result | python | def _query(event=None,
method='GET',
args=None,
header_dict=None,
data=None):
'''
Make a web call to IFTTT.
'''
secret_key = __salt__['config.get']('ifttt.secret_key') or \
__salt__['config.get']('ifttt:secret_key')
path = 'https://maker.ifttt.com/trigger/{0}/with/key/{1}'.format(event, secret_key)
if header_dict is None:
header_dict = {'Content-type': 'application/json'}
if method != 'POST':
header_dict['Accept'] = 'application/json'
result = salt.utils.http.query(
path,
method,
params={},
data=data,
header_dict=header_dict,
decode=True,
decode_type='auto',
text=True,
status=True,
cookies=True,
persist_session=True,
opts=__opts__,
backend='requests'
)
return result | [
"def",
"_query",
"(",
"event",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"args",
"=",
"None",
",",
"header_dict",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"secret_key",
"=",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'ifttt.secret_key'",
... | Make a web call to IFTTT. | [
"Make",
"a",
"web",
"call",
"to",
"IFTTT",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ifttt.py#L37-L70 | train |
saltstack/salt | salt/modules/ifttt.py | trigger_event | def trigger_event(event=None, **kwargs):
'''
Trigger a configured event in IFTTT.
:param event: The name of the event to trigger.
:return: A dictionary with status, text, and error if result was failure.
'''
res = {'result': False, 'message': 'Something went wrong'}
data = {}
for value in ('value1', 'value2', 'value3',
'Value1', 'Value2', 'Value3'):
if value in kwargs:
data[value.lower()] = kwargs[value]
data['occurredat'] = time.strftime("%B %d, %Y %I:%M%p", time.localtime())
result = _query(event=event,
method='POST',
data=salt.utils.json.dumps(data)
)
if 'status' in result:
if result['status'] == 200:
res['result'] = True
res['message'] = result['text']
else:
if 'error' in result:
res['message'] = result['error']
return res | python | def trigger_event(event=None, **kwargs):
'''
Trigger a configured event in IFTTT.
:param event: The name of the event to trigger.
:return: A dictionary with status, text, and error if result was failure.
'''
res = {'result': False, 'message': 'Something went wrong'}
data = {}
for value in ('value1', 'value2', 'value3',
'Value1', 'Value2', 'Value3'):
if value in kwargs:
data[value.lower()] = kwargs[value]
data['occurredat'] = time.strftime("%B %d, %Y %I:%M%p", time.localtime())
result = _query(event=event,
method='POST',
data=salt.utils.json.dumps(data)
)
if 'status' in result:
if result['status'] == 200:
res['result'] = True
res['message'] = result['text']
else:
if 'error' in result:
res['message'] = result['error']
return res | [
"def",
"trigger_event",
"(",
"event",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"{",
"'result'",
":",
"False",
",",
"'message'",
":",
"'Something went wrong'",
"}",
"data",
"=",
"{",
"}",
"for",
"value",
"in",
"(",
"'value1'",
",",
... | Trigger a configured event in IFTTT.
:param event: The name of the event to trigger.
:return: A dictionary with status, text, and error if result was failure. | [
"Trigger",
"a",
"configured",
"event",
"in",
"IFTTT",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ifttt.py#L73-L101 | train |
saltstack/salt | salt/proxy/napalm.py | init | def init(opts):
'''
Opens the connection with the network device.
'''
NETWORK_DEVICE.update(salt.utils.napalm.get_device(opts))
DETAILS['initialized'] = True
return True | python | def init(opts):
'''
Opens the connection with the network device.
'''
NETWORK_DEVICE.update(salt.utils.napalm.get_device(opts))
DETAILS['initialized'] = True
return True | [
"def",
"init",
"(",
"opts",
")",
":",
"NETWORK_DEVICE",
".",
"update",
"(",
"salt",
".",
"utils",
".",
"napalm",
".",
"get_device",
"(",
"opts",
")",
")",
"DETAILS",
"[",
"'initialized'",
"]",
"=",
"True",
"return",
"True"
] | Opens the connection with the network device. | [
"Opens",
"the",
"connection",
"with",
"the",
"network",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/napalm.py#L202-L208 | train |
saltstack/salt | salt/proxy/napalm.py | alive | def alive(opts):
'''
Return the connection status with the remote device.
.. versionadded:: 2017.7.0
'''
if salt.utils.napalm.not_always_alive(opts):
return True # don't force reconnection for not-always alive proxies
# or regular minion
is_alive_ret = call('is_alive', **{})
if not is_alive_ret.get('result', False):
log.debug(
'[%s] Unable to execute `is_alive`: %s',
opts.get('id'), is_alive_ret.get('comment')
)
# if `is_alive` is not implemented by the underneath driver,
# will consider the connection to be still alive
# we don't want overly request connection reestablishment
# NOTE: revisit this if IOS is still not stable
# and return False to force reconnection
return True
flag = is_alive_ret.get('out', {}).get('is_alive', False)
log.debug('Is %s still alive? %s', opts.get('id'), 'Yes.' if flag else 'No.')
return flag | python | def alive(opts):
'''
Return the connection status with the remote device.
.. versionadded:: 2017.7.0
'''
if salt.utils.napalm.not_always_alive(opts):
return True # don't force reconnection for not-always alive proxies
# or regular minion
is_alive_ret = call('is_alive', **{})
if not is_alive_ret.get('result', False):
log.debug(
'[%s] Unable to execute `is_alive`: %s',
opts.get('id'), is_alive_ret.get('comment')
)
# if `is_alive` is not implemented by the underneath driver,
# will consider the connection to be still alive
# we don't want overly request connection reestablishment
# NOTE: revisit this if IOS is still not stable
# and return False to force reconnection
return True
flag = is_alive_ret.get('out', {}).get('is_alive', False)
log.debug('Is %s still alive? %s', opts.get('id'), 'Yes.' if flag else 'No.')
return flag | [
"def",
"alive",
"(",
"opts",
")",
":",
"if",
"salt",
".",
"utils",
".",
"napalm",
".",
"not_always_alive",
"(",
"opts",
")",
":",
"return",
"True",
"# don't force reconnection for not-always alive proxies",
"# or regular minion",
"is_alive_ret",
"=",
"call",
"(",
... | Return the connection status with the remote device.
.. versionadded:: 2017.7.0 | [
"Return",
"the",
"connection",
"status",
"with",
"the",
"remote",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/napalm.py#L211-L234 | train |
saltstack/salt | salt/proxy/napalm.py | shutdown | def shutdown(opts):
'''
Closes connection with the device.
'''
try:
if not NETWORK_DEVICE.get('UP', False):
raise Exception('not connected!')
NETWORK_DEVICE.get('DRIVER').close()
except Exception as error:
port = NETWORK_DEVICE.get('OPTIONAL_ARGS', {}).get('port')
log.error(
'Cannot close connection with %s%s! Please check error: %s',
NETWORK_DEVICE.get('HOSTNAME', '[unknown hostname]'),
':{0}'.format(port) if port else '',
error
)
return True | python | def shutdown(opts):
'''
Closes connection with the device.
'''
try:
if not NETWORK_DEVICE.get('UP', False):
raise Exception('not connected!')
NETWORK_DEVICE.get('DRIVER').close()
except Exception as error:
port = NETWORK_DEVICE.get('OPTIONAL_ARGS', {}).get('port')
log.error(
'Cannot close connection with %s%s! Please check error: %s',
NETWORK_DEVICE.get('HOSTNAME', '[unknown hostname]'),
':{0}'.format(port) if port else '',
error
)
return True | [
"def",
"shutdown",
"(",
"opts",
")",
":",
"try",
":",
"if",
"not",
"NETWORK_DEVICE",
".",
"get",
"(",
"'UP'",
",",
"False",
")",
":",
"raise",
"Exception",
"(",
"'not connected!'",
")",
"NETWORK_DEVICE",
".",
"get",
"(",
"'DRIVER'",
")",
".",
"close",
... | Closes connection with the device. | [
"Closes",
"connection",
"with",
"the",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/napalm.py#L282-L299 | train |
saltstack/salt | salt/proxy/napalm.py | call | def call(method, *args, **kwargs):
'''
Calls a specific method from the network driver instance.
Please check the readthedocs_ page for the updated list of getters.
.. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix
:param method: specifies the name of the method to be called
:param params: contains the mapping between the name and the values of the parameters needed to call the method
:return: A dictionary with three keys:
- result (True/False): if the operation succeeded
- out (object): returns the object as-is from the call
- comment (string): provides more details in case the call failed
- traceback (string): complete traceback in case of exception. Please
submit an issue including this traceback on the `correct driver repo`_
and make sure to read the FAQ_
.. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new
.. _FAQ: https://github.com/napalm-automation/napalm#faq
Example:
.. code-block:: python
__proxy__['napalm.call']('cli'
**{
'commands': [
'show version',
'show chassis fan'
]
})
'''
kwargs_copy = {}
kwargs_copy.update(kwargs)
for karg, warg in six.iteritems(kwargs_copy):
# will remove None values
# thus the NAPALM methods will be called with their defaults
if warg is None:
kwargs.pop(karg)
return salt.utils.napalm.call(NETWORK_DEVICE, method, *args, **kwargs) | python | def call(method, *args, **kwargs):
'''
Calls a specific method from the network driver instance.
Please check the readthedocs_ page for the updated list of getters.
.. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix
:param method: specifies the name of the method to be called
:param params: contains the mapping between the name and the values of the parameters needed to call the method
:return: A dictionary with three keys:
- result (True/False): if the operation succeeded
- out (object): returns the object as-is from the call
- comment (string): provides more details in case the call failed
- traceback (string): complete traceback in case of exception. Please
submit an issue including this traceback on the `correct driver repo`_
and make sure to read the FAQ_
.. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new
.. _FAQ: https://github.com/napalm-automation/napalm#faq
Example:
.. code-block:: python
__proxy__['napalm.call']('cli'
**{
'commands': [
'show version',
'show chassis fan'
]
})
'''
kwargs_copy = {}
kwargs_copy.update(kwargs)
for karg, warg in six.iteritems(kwargs_copy):
# will remove None values
# thus the NAPALM methods will be called with their defaults
if warg is None:
kwargs.pop(karg)
return salt.utils.napalm.call(NETWORK_DEVICE, method, *args, **kwargs) | [
"def",
"call",
"(",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs_copy",
"=",
"{",
"}",
"kwargs_copy",
".",
"update",
"(",
"kwargs",
")",
"for",
"karg",
",",
"warg",
"in",
"six",
".",
"iteritems",
"(",
"kwargs_copy",
")",
"... | Calls a specific method from the network driver instance.
Please check the readthedocs_ page for the updated list of getters.
.. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix
:param method: specifies the name of the method to be called
:param params: contains the mapping between the name and the values of the parameters needed to call the method
:return: A dictionary with three keys:
- result (True/False): if the operation succeeded
- out (object): returns the object as-is from the call
- comment (string): provides more details in case the call failed
- traceback (string): complete traceback in case of exception. Please
submit an issue including this traceback on the `correct driver repo`_
and make sure to read the FAQ_
.. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new
.. _FAQ: https://github.com/napalm-automation/napalm#faq
Example:
.. code-block:: python
__proxy__['napalm.call']('cli'
**{
'commands': [
'show version',
'show chassis fan'
]
}) | [
"Calls",
"a",
"specific",
"method",
"from",
"the",
"network",
"driver",
"instance",
".",
"Please",
"check",
"the",
"readthedocs_",
"page",
"for",
"the",
"updated",
"list",
"of",
"getters",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/napalm.py#L306-L346 | train |
saltstack/salt | salt/modules/win_license.py | info | def info():
'''
Return information about the license, if the license is not
correctly activated this will return None.
CLI Example:
.. code-block:: bash
salt '*' license.info
'''
cmd = r'cscript C:\Windows\System32\slmgr.vbs /dli'
out = __salt__['cmd.run'](cmd)
match = re.search(r'Name: (.*)\r\nDescription: (.*)\r\nPartial Product Key: (.*)\r\nLicense Status: (.*)', out,
re.MULTILINE)
if match is not None:
groups = match.groups()
return {
'name': groups[0],
'description': groups[1],
'partial_key': groups[2],
'licensed': 'Licensed' in groups[3]
}
return None | python | def info():
'''
Return information about the license, if the license is not
correctly activated this will return None.
CLI Example:
.. code-block:: bash
salt '*' license.info
'''
cmd = r'cscript C:\Windows\System32\slmgr.vbs /dli'
out = __salt__['cmd.run'](cmd)
match = re.search(r'Name: (.*)\r\nDescription: (.*)\r\nPartial Product Key: (.*)\r\nLicense Status: (.*)', out,
re.MULTILINE)
if match is not None:
groups = match.groups()
return {
'name': groups[0],
'description': groups[1],
'partial_key': groups[2],
'licensed': 'Licensed' in groups[3]
}
return None | [
"def",
"info",
"(",
")",
":",
"cmd",
"=",
"r'cscript C:\\Windows\\System32\\slmgr.vbs /dli'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
"match",
"=",
"re",
".",
"search",
"(",
"r'Name: (.*)\\r\\nDescription: (.*)\\r\\nPartial Product Key: (.*)\\r\\... | Return information about the license, if the license is not
correctly activated this will return None.
CLI Example:
.. code-block:: bash
salt '*' license.info | [
"Return",
"information",
"about",
"the",
"license",
"if",
"the",
"license",
"is",
"not",
"correctly",
"activated",
"this",
"will",
"return",
"None",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_license.py#L106-L132 | train |
saltstack/salt | salt/states/boto_apigateway.py | present | def present(name, api_name, swagger_file, stage_name, api_key_required,
lambda_integration_role, lambda_region=None, stage_variables=None,
region=None, key=None, keyid=None, profile=None,
lambda_funcname_format='{stage}_{api}_{resource}_{method}',
authorization_type='NONE', error_response_template=None, response_template=None):
'''
Ensure the spcified api_name with the corresponding swaggerfile is deployed to the
given stage_name in AWS ApiGateway.
this state currently only supports ApiGateway integration with AWS Lambda, and CORS support is
handled through a Mock integration.
There may be multiple deployments for the API object, each deployment is tagged with a description
(i.e. unique label) in pretty printed json format consisting of the following key/values.
.. code-block:: text
{
"api_name": api_name,
"swagger_file": basename_of_swagger_file
"swagger_file_md5sum": md5sum_of_swagger_file,
"swagger_info_object": info_object_content_in_swagger_file
}
Please note that the name of the lambda function to be integrated will be derived
via the provided lambda_funcname_format parameters:
- the default lambda_funcname_format is a string with the following
substitutable keys: "{stage}_{api}_{resource}_{method}". The user can
choose to reorder the known keys.
- the stage key corresponds to the stage_name passed in.
- the api key corresponds to the api_name passed in.
- the resource corresponds to the resource path defined in the passed swagger file.
- the method corresponds to the method for a resource path defined in the passed swagger file.
For the default lambda_funcname_format, given the following input:
.. code-block:: python
api_name = ' Test Service'
stage_name = 'alpha'
basePath = '/api'
path = '/a/{b}/c'
method = 'POST'
We will end up with the following Lambda Function Name that will be looked
up: 'test_service_alpha_a_b_c_post'
The canconicalization of these input parameters is done in the following order:
1. lambda_funcname_format is formatted with the input parameters as passed,
2. resulting string is stripped for leading/trailing spaces,
3. path parameter's curly braces are removed from the resource path,
4. consecutive spaces and forward slashes in the paths are replaced with '_'
5. consecutive '_' are replaced with '_'
Please note that for error response handling, the swagger file must have an error response model
with the following schema. The lambda functions should throw exceptions for any non successful responses.
An optional pattern field can be specified in errorMessage field to aid the response mapping from Lambda
to the proper error return status codes.
.. code-block:: yaml
Error:
type: object
properties:
stackTrace:
type: array
items:
type: array
items:
type: string
description: call stack
errorType:
type: string
description: error type
errorMessage:
type: string
description: |
Error message, will be matched based on pattern.
If no pattern is specified, the default pattern used for response mapping will be +*.
name
The name of the state definition
api_name
The name of the rest api that we want to ensure exists in AWS API Gateway
swagger_file
Name of the location of the swagger rest api definition file in YAML format.
stage_name
Name of the stage we want to be associated with the given api_name and swagger_file
definition
api_key_required
True or False - whether the API Key is required to call API methods
lambda_integration_role
The name or ARN of the IAM role that the AWS ApiGateway assumes when it
executes your lambda function to handle incoming requests
lambda_region
The region where we expect to find the lambda functions. This is used to
determine the region where we should look for the Lambda Function for
integration purposes. The region determination is based on the following
priority:
1. lambda_region as passed in (is not None)
2. if lambda_region is None, use the region as if a boto_lambda
function were executed without explicitly specifying lambda region.
3. if region determined in (2) is different than the region used by
boto_apigateway functions, a final lookup will be attempted using
the boto_apigateway region.
stage_variables
A dict with variables and their values, or a pillar key (string) that
contains a dict with variables and their values.
key and values in the dict must be strings. {'string': 'string'}
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
lambda_funcname_format
Please review the earlier example for the usage. The only substituable keys in the funcname
format are {stage}, {api}, {resource}, {method}.
Any other keys or positional subsitution parameters will be flagged as an invalid input.
authorization_type
This field can be either 'NONE', or 'AWS_IAM'. This will be applied to all methods in the given
swagger spec file. Default is set to 'NONE'
error_response_template
String value that defines the response template mapping that should be applied in cases error occurs.
Refer to AWS documentation for details: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
If set to None, the following default value is used:
.. code-block:: text
'#set($inputRoot = $input.path(\'$\'))\\n'
'{\\n'
' "errorMessage" : "$inputRoot.errorMessage",\\n'
' "errorType" : "$inputRoot.errorType",\\n'
' "stackTrace" : [\\n'
'#foreach($stackTrace in $inputRoot.stackTrace)\\n'
' [\\n'
'#foreach($elem in $stackTrace)\\n'
' "$elem"\\n'
'#if($foreach.hasNext),#end\\n'
'#end\\n'
' ]\\n'
'#if($foreach.hasNext),#end\\n'
'#end\\n'
' ]\\n'
.. versionadded:: 2017.7.0
response_template
String value that defines the response template mapping applied in case
of success (including OPTIONS method) If set to None, empty ({})
template is assumed, which will transfer response from the lambda
function as is.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
# try to open the swagger file and basic validation
swagger = _Swagger(api_name, stage_name,
lambda_funcname_format,
swagger_file,
error_response_template, response_template,
common_args)
# retrieve stage variables
stage_vars = _get_stage_variables(stage_variables)
# verify if api and stage already exists
ret = swagger.verify_api(ret)
if ret.get('publish'):
# there is a deployment label with signature matching the given api_name,
# swagger file name, swagger file md5 sum, and swagger file info object
# just reassociate the stage_name to the given deployment label.
if __opts__['test']:
ret['comment'] = ('[stage: {0}] will be reassociated to an already available '
'deployment that matched the given [api_name: {1}] '
'and [swagger_file: {2}].\n'
'Stage variables will be set '
'to {3}.'.format(stage_name, api_name, swagger_file, stage_vars))
ret['result'] = None
return ret
return swagger.publish_api(ret, stage_vars)
if ret.get('current'):
# already at desired state for the stage, swagger_file, and api_name
if __opts__['test']:
ret['comment'] = ('[stage: {0}] is already at desired state with an associated '
'deployment matching the given [api_name: {1}] '
'and [swagger_file: {2}].\n'
'Stage variables will be set '
'to {3}.'.format(stage_name, api_name, swagger_file, stage_vars))
ret['result'] = None
return swagger.overwrite_stage_variables(ret, stage_vars)
# there doesn't exist any previous deployments for the given swagger_file, we need
# to redeploy the content of the swagger file to the api, models, and resources object
# and finally create a new deployment and tie the stage_name to this new deployment
if __opts__['test']:
ret['comment'] = ('There is no deployment matching the given [api_name: {0}] '
'and [swagger_file: {1}]. A new deployment will be '
'created and the [stage_name: {2}] will then be associated '
'to the newly created deployment.\n'
'Stage variables will be set '
'to {3}.'.format(api_name, swagger_file, stage_name, stage_vars))
ret['result'] = None
return ret
ret = swagger.deploy_api(ret)
if ret.get('abort'):
return ret
ret = swagger.deploy_models(ret)
if ret.get('abort'):
return ret
ret = swagger.deploy_resources(ret,
api_key_required=api_key_required,
lambda_integration_role=lambda_integration_role,
lambda_region=lambda_region,
authorization_type=authorization_type)
if ret.get('abort'):
return ret
ret = swagger.publish_api(ret, stage_vars)
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | python | def present(name, api_name, swagger_file, stage_name, api_key_required,
lambda_integration_role, lambda_region=None, stage_variables=None,
region=None, key=None, keyid=None, profile=None,
lambda_funcname_format='{stage}_{api}_{resource}_{method}',
authorization_type='NONE', error_response_template=None, response_template=None):
'''
Ensure the spcified api_name with the corresponding swaggerfile is deployed to the
given stage_name in AWS ApiGateway.
this state currently only supports ApiGateway integration with AWS Lambda, and CORS support is
handled through a Mock integration.
There may be multiple deployments for the API object, each deployment is tagged with a description
(i.e. unique label) in pretty printed json format consisting of the following key/values.
.. code-block:: text
{
"api_name": api_name,
"swagger_file": basename_of_swagger_file
"swagger_file_md5sum": md5sum_of_swagger_file,
"swagger_info_object": info_object_content_in_swagger_file
}
Please note that the name of the lambda function to be integrated will be derived
via the provided lambda_funcname_format parameters:
- the default lambda_funcname_format is a string with the following
substitutable keys: "{stage}_{api}_{resource}_{method}". The user can
choose to reorder the known keys.
- the stage key corresponds to the stage_name passed in.
- the api key corresponds to the api_name passed in.
- the resource corresponds to the resource path defined in the passed swagger file.
- the method corresponds to the method for a resource path defined in the passed swagger file.
For the default lambda_funcname_format, given the following input:
.. code-block:: python
api_name = ' Test Service'
stage_name = 'alpha'
basePath = '/api'
path = '/a/{b}/c'
method = 'POST'
We will end up with the following Lambda Function Name that will be looked
up: 'test_service_alpha_a_b_c_post'
The canconicalization of these input parameters is done in the following order:
1. lambda_funcname_format is formatted with the input parameters as passed,
2. resulting string is stripped for leading/trailing spaces,
3. path parameter's curly braces are removed from the resource path,
4. consecutive spaces and forward slashes in the paths are replaced with '_'
5. consecutive '_' are replaced with '_'
Please note that for error response handling, the swagger file must have an error response model
with the following schema. The lambda functions should throw exceptions for any non successful responses.
An optional pattern field can be specified in errorMessage field to aid the response mapping from Lambda
to the proper error return status codes.
.. code-block:: yaml
Error:
type: object
properties:
stackTrace:
type: array
items:
type: array
items:
type: string
description: call stack
errorType:
type: string
description: error type
errorMessage:
type: string
description: |
Error message, will be matched based on pattern.
If no pattern is specified, the default pattern used for response mapping will be +*.
name
The name of the state definition
api_name
The name of the rest api that we want to ensure exists in AWS API Gateway
swagger_file
Name of the location of the swagger rest api definition file in YAML format.
stage_name
Name of the stage we want to be associated with the given api_name and swagger_file
definition
api_key_required
True or False - whether the API Key is required to call API methods
lambda_integration_role
The name or ARN of the IAM role that the AWS ApiGateway assumes when it
executes your lambda function to handle incoming requests
lambda_region
The region where we expect to find the lambda functions. This is used to
determine the region where we should look for the Lambda Function for
integration purposes. The region determination is based on the following
priority:
1. lambda_region as passed in (is not None)
2. if lambda_region is None, use the region as if a boto_lambda
function were executed without explicitly specifying lambda region.
3. if region determined in (2) is different than the region used by
boto_apigateway functions, a final lookup will be attempted using
the boto_apigateway region.
stage_variables
A dict with variables and their values, or a pillar key (string) that
contains a dict with variables and their values.
key and values in the dict must be strings. {'string': 'string'}
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
lambda_funcname_format
Please review the earlier example for the usage. The only substituable keys in the funcname
format are {stage}, {api}, {resource}, {method}.
Any other keys or positional subsitution parameters will be flagged as an invalid input.
authorization_type
This field can be either 'NONE', or 'AWS_IAM'. This will be applied to all methods in the given
swagger spec file. Default is set to 'NONE'
error_response_template
String value that defines the response template mapping that should be applied in cases error occurs.
Refer to AWS documentation for details: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
If set to None, the following default value is used:
.. code-block:: text
'#set($inputRoot = $input.path(\'$\'))\\n'
'{\\n'
' "errorMessage" : "$inputRoot.errorMessage",\\n'
' "errorType" : "$inputRoot.errorType",\\n'
' "stackTrace" : [\\n'
'#foreach($stackTrace in $inputRoot.stackTrace)\\n'
' [\\n'
'#foreach($elem in $stackTrace)\\n'
' "$elem"\\n'
'#if($foreach.hasNext),#end\\n'
'#end\\n'
' ]\\n'
'#if($foreach.hasNext),#end\\n'
'#end\\n'
' ]\\n'
.. versionadded:: 2017.7.0
response_template
String value that defines the response template mapping applied in case
of success (including OPTIONS method) If set to None, empty ({})
template is assumed, which will transfer response from the lambda
function as is.
.. versionadded:: 2017.7.0
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
# try to open the swagger file and basic validation
swagger = _Swagger(api_name, stage_name,
lambda_funcname_format,
swagger_file,
error_response_template, response_template,
common_args)
# retrieve stage variables
stage_vars = _get_stage_variables(stage_variables)
# verify if api and stage already exists
ret = swagger.verify_api(ret)
if ret.get('publish'):
# there is a deployment label with signature matching the given api_name,
# swagger file name, swagger file md5 sum, and swagger file info object
# just reassociate the stage_name to the given deployment label.
if __opts__['test']:
ret['comment'] = ('[stage: {0}] will be reassociated to an already available '
'deployment that matched the given [api_name: {1}] '
'and [swagger_file: {2}].\n'
'Stage variables will be set '
'to {3}.'.format(stage_name, api_name, swagger_file, stage_vars))
ret['result'] = None
return ret
return swagger.publish_api(ret, stage_vars)
if ret.get('current'):
# already at desired state for the stage, swagger_file, and api_name
if __opts__['test']:
ret['comment'] = ('[stage: {0}] is already at desired state with an associated '
'deployment matching the given [api_name: {1}] '
'and [swagger_file: {2}].\n'
'Stage variables will be set '
'to {3}.'.format(stage_name, api_name, swagger_file, stage_vars))
ret['result'] = None
return swagger.overwrite_stage_variables(ret, stage_vars)
# there doesn't exist any previous deployments for the given swagger_file, we need
# to redeploy the content of the swagger file to the api, models, and resources object
# and finally create a new deployment and tie the stage_name to this new deployment
if __opts__['test']:
ret['comment'] = ('There is no deployment matching the given [api_name: {0}] '
'and [swagger_file: {1}]. A new deployment will be '
'created and the [stage_name: {2}] will then be associated '
'to the newly created deployment.\n'
'Stage variables will be set '
'to {3}.'.format(api_name, swagger_file, stage_name, stage_vars))
ret['result'] = None
return ret
ret = swagger.deploy_api(ret)
if ret.get('abort'):
return ret
ret = swagger.deploy_models(ret)
if ret.get('abort'):
return ret
ret = swagger.deploy_resources(ret,
api_key_required=api_key_required,
lambda_integration_role=lambda_integration_role,
lambda_region=lambda_region,
authorization_type=authorization_type)
if ret.get('abort'):
return ret
ret = swagger.publish_api(ret, stage_vars)
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | [
"def",
"present",
"(",
"name",
",",
"api_name",
",",
"swagger_file",
",",
"stage_name",
",",
"api_key_required",
",",
"lambda_integration_role",
",",
"lambda_region",
"=",
"None",
",",
"stage_variables",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"="... | Ensure the spcified api_name with the corresponding swaggerfile is deployed to the
given stage_name in AWS ApiGateway.
this state currently only supports ApiGateway integration with AWS Lambda, and CORS support is
handled through a Mock integration.
There may be multiple deployments for the API object, each deployment is tagged with a description
(i.e. unique label) in pretty printed json format consisting of the following key/values.
.. code-block:: text
{
"api_name": api_name,
"swagger_file": basename_of_swagger_file
"swagger_file_md5sum": md5sum_of_swagger_file,
"swagger_info_object": info_object_content_in_swagger_file
}
Please note that the name of the lambda function to be integrated will be derived
via the provided lambda_funcname_format parameters:
- the default lambda_funcname_format is a string with the following
substitutable keys: "{stage}_{api}_{resource}_{method}". The user can
choose to reorder the known keys.
- the stage key corresponds to the stage_name passed in.
- the api key corresponds to the api_name passed in.
- the resource corresponds to the resource path defined in the passed swagger file.
- the method corresponds to the method for a resource path defined in the passed swagger file.
For the default lambda_funcname_format, given the following input:
.. code-block:: python
api_name = ' Test Service'
stage_name = 'alpha'
basePath = '/api'
path = '/a/{b}/c'
method = 'POST'
We will end up with the following Lambda Function Name that will be looked
up: 'test_service_alpha_a_b_c_post'
The canconicalization of these input parameters is done in the following order:
1. lambda_funcname_format is formatted with the input parameters as passed,
2. resulting string is stripped for leading/trailing spaces,
3. path parameter's curly braces are removed from the resource path,
4. consecutive spaces and forward slashes in the paths are replaced with '_'
5. consecutive '_' are replaced with '_'
Please note that for error response handling, the swagger file must have an error response model
with the following schema. The lambda functions should throw exceptions for any non successful responses.
An optional pattern field can be specified in errorMessage field to aid the response mapping from Lambda
to the proper error return status codes.
.. code-block:: yaml
Error:
type: object
properties:
stackTrace:
type: array
items:
type: array
items:
type: string
description: call stack
errorType:
type: string
description: error type
errorMessage:
type: string
description: |
Error message, will be matched based on pattern.
If no pattern is specified, the default pattern used for response mapping will be +*.
name
The name of the state definition
api_name
The name of the rest api that we want to ensure exists in AWS API Gateway
swagger_file
Name of the location of the swagger rest api definition file in YAML format.
stage_name
Name of the stage we want to be associated with the given api_name and swagger_file
definition
api_key_required
True or False - whether the API Key is required to call API methods
lambda_integration_role
The name or ARN of the IAM role that the AWS ApiGateway assumes when it
executes your lambda function to handle incoming requests
lambda_region
The region where we expect to find the lambda functions. This is used to
determine the region where we should look for the Lambda Function for
integration purposes. The region determination is based on the following
priority:
1. lambda_region as passed in (is not None)
2. if lambda_region is None, use the region as if a boto_lambda
function were executed without explicitly specifying lambda region.
3. if region determined in (2) is different than the region used by
boto_apigateway functions, a final lookup will be attempted using
the boto_apigateway region.
stage_variables
A dict with variables and their values, or a pillar key (string) that
contains a dict with variables and their values.
key and values in the dict must be strings. {'string': 'string'}
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
lambda_funcname_format
Please review the earlier example for the usage. The only substituable keys in the funcname
format are {stage}, {api}, {resource}, {method}.
Any other keys or positional subsitution parameters will be flagged as an invalid input.
authorization_type
This field can be either 'NONE', or 'AWS_IAM'. This will be applied to all methods in the given
swagger spec file. Default is set to 'NONE'
error_response_template
String value that defines the response template mapping that should be applied in cases error occurs.
Refer to AWS documentation for details: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
If set to None, the following default value is used:
.. code-block:: text
'#set($inputRoot = $input.path(\'$\'))\\n'
'{\\n'
' "errorMessage" : "$inputRoot.errorMessage",\\n'
' "errorType" : "$inputRoot.errorType",\\n'
' "stackTrace" : [\\n'
'#foreach($stackTrace in $inputRoot.stackTrace)\\n'
' [\\n'
'#foreach($elem in $stackTrace)\\n'
' "$elem"\\n'
'#if($foreach.hasNext),#end\\n'
'#end\\n'
' ]\\n'
'#if($foreach.hasNext),#end\\n'
'#end\\n'
' ]\\n'
.. versionadded:: 2017.7.0
response_template
String value that defines the response template mapping applied in case
of success (including OPTIONS method) If set to None, empty ({})
template is assumed, which will transfer response from the lambda
function as is.
.. versionadded:: 2017.7.0 | [
"Ensure",
"the",
"spcified",
"api_name",
"with",
"the",
"corresponding",
"swaggerfile",
"is",
"deployed",
"to",
"the",
"given",
"stage_name",
"in",
"AWS",
"ApiGateway",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L79-L339 | train |
saltstack/salt | salt/states/boto_apigateway.py | _get_stage_variables | def _get_stage_variables(stage_variables):
'''
Helper function to retrieve stage variables from pillars/options, if the
input is a string
'''
ret = dict()
if stage_variables is None:
return ret
if isinstance(stage_variables, six.string_types):
if stage_variables in __opts__:
ret = __opts__[stage_variables]
master_opts = __pillar__.get('master', {})
if stage_variables in master_opts:
ret = master_opts[stage_variables]
if stage_variables in __pillar__:
ret = __pillar__[stage_variables]
elif isinstance(stage_variables, dict):
ret = stage_variables
if not isinstance(ret, dict):
ret = dict()
return ret | python | def _get_stage_variables(stage_variables):
'''
Helper function to retrieve stage variables from pillars/options, if the
input is a string
'''
ret = dict()
if stage_variables is None:
return ret
if isinstance(stage_variables, six.string_types):
if stage_variables in __opts__:
ret = __opts__[stage_variables]
master_opts = __pillar__.get('master', {})
if stage_variables in master_opts:
ret = master_opts[stage_variables]
if stage_variables in __pillar__:
ret = __pillar__[stage_variables]
elif isinstance(stage_variables, dict):
ret = stage_variables
if not isinstance(ret, dict):
ret = dict()
return ret | [
"def",
"_get_stage_variables",
"(",
"stage_variables",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"if",
"stage_variables",
"is",
"None",
":",
"return",
"ret",
"if",
"isinstance",
"(",
"stage_variables",
",",
"six",
".",
"string_types",
")",
":",
"if",
"stage_va... | Helper function to retrieve stage variables from pillars/options, if the
input is a string | [
"Helper",
"function",
"to",
"retrieve",
"stage",
"variables",
"from",
"pillars",
"/",
"options",
"if",
"the",
"input",
"is",
"a",
"string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L342-L365 | train |
saltstack/salt | salt/states/boto_apigateway.py | absent | def absent(name, api_name, stage_name, nuke_api=False, region=None, key=None, keyid=None, profile=None):
'''
Ensure the stage_name associated with the given api_name deployed by boto_apigateway's
present state is removed. If the currently associated deployment to the given stage_name has
no other stages associated with it, the deployment will also be removed.
name
Name of the swagger file in YAML format
api_name
Name of the rest api on AWS ApiGateway to ensure is absent.
stage_name
Name of the stage to be removed irrespective of the swagger file content.
If the current deployment associated with the stage_name has no other stages associated
with it, the deployment will also be removed.
nuke_api
If True, removes the API itself only if there are no other stages associated with any other
deployments once the given stage_name is removed.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
swagger = _Swagger(api_name, stage_name, '', None, None, None, common_args)
if not swagger.restApiId:
ret['comment'] = '[Rest API: {0}] does not exist.'.format(api_name)
return ret
if __opts__['test']:
if nuke_api:
ret['comment'] = ('[stage: {0}] will be deleted, if there are no other '
'active stages, the [api: {1} will also be '
'deleted.'.format(stage_name, api_name))
else:
ret['comment'] = ('[stage: {0}] will be deleted.'.format(stage_name))
ret['result'] = None
return ret
ret = swagger.delete_stage(ret)
if ret.get('abort'):
return ret
if nuke_api and swagger.no_more_deployments_remain():
ret = swagger.delete_api(ret)
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | python | def absent(name, api_name, stage_name, nuke_api=False, region=None, key=None, keyid=None, profile=None):
'''
Ensure the stage_name associated with the given api_name deployed by boto_apigateway's
present state is removed. If the currently associated deployment to the given stage_name has
no other stages associated with it, the deployment will also be removed.
name
Name of the swagger file in YAML format
api_name
Name of the rest api on AWS ApiGateway to ensure is absent.
stage_name
Name of the stage to be removed irrespective of the swagger file content.
If the current deployment associated with the stage_name has no other stages associated
with it, the deployment will also be removed.
nuke_api
If True, removes the API itself only if there are no other stages associated with any other
deployments once the given stage_name is removed.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
swagger = _Swagger(api_name, stage_name, '', None, None, None, common_args)
if not swagger.restApiId:
ret['comment'] = '[Rest API: {0}] does not exist.'.format(api_name)
return ret
if __opts__['test']:
if nuke_api:
ret['comment'] = ('[stage: {0}] will be deleted, if there are no other '
'active stages, the [api: {1} will also be '
'deleted.'.format(stage_name, api_name))
else:
ret['comment'] = ('[stage: {0}] will be deleted.'.format(stage_name))
ret['result'] = None
return ret
ret = swagger.delete_stage(ret)
if ret.get('abort'):
return ret
if nuke_api and swagger.no_more_deployments_remain():
ret = swagger.delete_api(ret)
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | [
"def",
"absent",
"(",
"name",
",",
"api_name",
",",
"stage_name",
",",
"nuke_api",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
... | Ensure the stage_name associated with the given api_name deployed by boto_apigateway's
present state is removed. If the currently associated deployment to the given stage_name has
no other stages associated with it, the deployment will also be removed.
name
Name of the swagger file in YAML format
api_name
Name of the rest api on AWS ApiGateway to ensure is absent.
stage_name
Name of the stage to be removed irrespective of the swagger file content.
If the current deployment associated with the stage_name has no other stages associated
with it, the deployment will also be removed.
nuke_api
If True, removes the API itself only if there are no other stages associated with any other
deployments once the given stage_name is removed.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"the",
"stage_name",
"associated",
"with",
"the",
"given",
"api_name",
"deployed",
"by",
"boto_apigateway",
"s",
"present",
"state",
"is",
"removed",
".",
"If",
"the",
"currently",
"associated",
"deployment",
"to",
"the",
"given",
"stage_name",
"has",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L368-L443 | train |
saltstack/salt | salt/states/boto_apigateway.py | _gen_md5_filehash | def _gen_md5_filehash(fname, *args):
'''
helper function to generate a md5 hash of the swagger definition file
any extra argument passed to the function is converted to a string
and participates in the hash calculation
'''
_hash = hashlib.md5()
with salt.utils.files.fopen(fname, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
_hash.update(chunk)
for extra_arg in args:
_hash.update(six.b(str(extra_arg)))
return _hash.hexdigest() | python | def _gen_md5_filehash(fname, *args):
'''
helper function to generate a md5 hash of the swagger definition file
any extra argument passed to the function is converted to a string
and participates in the hash calculation
'''
_hash = hashlib.md5()
with salt.utils.files.fopen(fname, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
_hash.update(chunk)
for extra_arg in args:
_hash.update(six.b(str(extra_arg)))
return _hash.hexdigest() | [
"def",
"_gen_md5_filehash",
"(",
"fname",
",",
"*",
"args",
")",
":",
"_hash",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"fname",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"... | helper function to generate a md5 hash of the swagger definition file
any extra argument passed to the function is converted to a string
and participates in the hash calculation | [
"helper",
"function",
"to",
"generate",
"a",
"md5",
"hash",
"of",
"the",
"swagger",
"definition",
"file",
"any",
"extra",
"argument",
"passed",
"to",
"the",
"function",
"is",
"converted",
"to",
"a",
"string",
"and",
"participates",
"in",
"the",
"hash",
"calc... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L447-L460 | train |
saltstack/salt | salt/states/boto_apigateway.py | _dict_to_json_pretty | def _dict_to_json_pretty(d, sort_keys=True):
'''
helper function to generate pretty printed json output
'''
return salt.utils.json.dumps(d, indent=4, separators=(',', ': '), sort_keys=sort_keys) | python | def _dict_to_json_pretty(d, sort_keys=True):
'''
helper function to generate pretty printed json output
'''
return salt.utils.json.dumps(d, indent=4, separators=(',', ': '), sort_keys=sort_keys) | [
"def",
"_dict_to_json_pretty",
"(",
"d",
",",
"sort_keys",
"=",
"True",
")",
":",
"return",
"salt",
".",
"utils",
".",
"json",
".",
"dumps",
"(",
"d",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
",",
"sort_keys",
... | helper function to generate pretty printed json output | [
"helper",
"function",
"to",
"generate",
"pretty",
"printed",
"json",
"output"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L463-L467 | train |
saltstack/salt | salt/states/boto_apigateway.py | _name_matches | def _name_matches(name, matches):
'''
Helper function to see if given name has any of the patterns in given matches
'''
for m in matches:
if name.endswith(m):
return True
if name.lower().endswith('_' + m.lower()):
return True
if name.lower() == m.lower():
return True
return False | python | def _name_matches(name, matches):
'''
Helper function to see if given name has any of the patterns in given matches
'''
for m in matches:
if name.endswith(m):
return True
if name.lower().endswith('_' + m.lower()):
return True
if name.lower() == m.lower():
return True
return False | [
"def",
"_name_matches",
"(",
"name",
",",
"matches",
")",
":",
"for",
"m",
"in",
"matches",
":",
"if",
"name",
".",
"endswith",
"(",
"m",
")",
":",
"return",
"True",
"if",
"name",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'_'",
"+",
"m",
"."... | Helper function to see if given name has any of the patterns in given matches | [
"Helper",
"function",
"to",
"see",
"if",
"given",
"name",
"has",
"any",
"of",
"the",
"patterns",
"in",
"given",
"matches"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L472-L483 | train |
saltstack/salt | salt/states/boto_apigateway.py | _object_reducer | def _object_reducer(o, names=('id', 'name', 'path', 'httpMethod',
'statusCode', 'Created', 'Deleted',
'Updated', 'Flushed', 'Associated', 'Disassociated')):
'''
Helper function to reduce the amount of information that will be kept in the change log
for API GW related return values
'''
result = {}
if isinstance(o, dict):
for k, v in six.iteritems(o):
if isinstance(v, dict):
reduced = v if k == 'variables' else _object_reducer(v, names)
if reduced or _name_matches(k, names):
result[k] = reduced
elif isinstance(v, list):
newlist = []
for val in v:
reduced = _object_reducer(val, names)
if reduced or _name_matches(k, names):
newlist.append(reduced)
if newlist:
result[k] = newlist
else:
if _name_matches(k, names):
result[k] = v
return result | python | def _object_reducer(o, names=('id', 'name', 'path', 'httpMethod',
'statusCode', 'Created', 'Deleted',
'Updated', 'Flushed', 'Associated', 'Disassociated')):
'''
Helper function to reduce the amount of information that will be kept in the change log
for API GW related return values
'''
result = {}
if isinstance(o, dict):
for k, v in six.iteritems(o):
if isinstance(v, dict):
reduced = v if k == 'variables' else _object_reducer(v, names)
if reduced or _name_matches(k, names):
result[k] = reduced
elif isinstance(v, list):
newlist = []
for val in v:
reduced = _object_reducer(val, names)
if reduced or _name_matches(k, names):
newlist.append(reduced)
if newlist:
result[k] = newlist
else:
if _name_matches(k, names):
result[k] = v
return result | [
"def",
"_object_reducer",
"(",
"o",
",",
"names",
"=",
"(",
"'id'",
",",
"'name'",
",",
"'path'",
",",
"'httpMethod'",
",",
"'statusCode'",
",",
"'Created'",
",",
"'Deleted'",
",",
"'Updated'",
",",
"'Flushed'",
",",
"'Associated'",
",",
"'Disassociated'",
"... | Helper function to reduce the amount of information that will be kept in the change log
for API GW related return values | [
"Helper",
"function",
"to",
"reduce",
"the",
"amount",
"of",
"information",
"that",
"will",
"be",
"kept",
"in",
"the",
"change",
"log",
"for",
"API",
"GW",
"related",
"return",
"values"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L486-L511 | train |
saltstack/salt | salt/states/boto_apigateway.py | _log_changes | def _log_changes(ret, changekey, changevalue):
'''
For logging create/update/delete operations to AWS ApiGateway
'''
cl = ret['changes'].get('new', [])
cl.append({changekey: _object_reducer(changevalue)})
ret['changes']['new'] = cl
return ret | python | def _log_changes(ret, changekey, changevalue):
'''
For logging create/update/delete operations to AWS ApiGateway
'''
cl = ret['changes'].get('new', [])
cl.append({changekey: _object_reducer(changevalue)})
ret['changes']['new'] = cl
return ret | [
"def",
"_log_changes",
"(",
"ret",
",",
"changekey",
",",
"changevalue",
")",
":",
"cl",
"=",
"ret",
"[",
"'changes'",
"]",
".",
"get",
"(",
"'new'",
",",
"[",
"]",
")",
"cl",
".",
"append",
"(",
"{",
"changekey",
":",
"_object_reducer",
"(",
"change... | For logging create/update/delete operations to AWS ApiGateway | [
"For",
"logging",
"create",
"/",
"update",
"/",
"delete",
"operations",
"to",
"AWS",
"ApiGateway"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L514-L521 | train |
saltstack/salt | salt/states/boto_apigateway.py | _log_error_and_abort | def _log_error_and_abort(ret, obj):
'''
helper function to update errors in the return structure
'''
ret['result'] = False
ret['abort'] = True
if 'error' in obj:
ret['comment'] = '{0}'.format(obj.get('error'))
return ret | python | def _log_error_and_abort(ret, obj):
'''
helper function to update errors in the return structure
'''
ret['result'] = False
ret['abort'] = True
if 'error' in obj:
ret['comment'] = '{0}'.format(obj.get('error'))
return ret | [
"def",
"_log_error_and_abort",
"(",
"ret",
",",
"obj",
")",
":",
"ret",
"[",
"'result'",
"]",
"=",
"False",
"ret",
"[",
"'abort'",
"]",
"=",
"True",
"if",
"'error'",
"in",
"obj",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'{0}'",
".",
"format",
"(",
... | helper function to update errors in the return structure | [
"helper",
"function",
"to",
"update",
"errors",
"in",
"the",
"return",
"structure"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L524-L532 | train |
saltstack/salt | salt/states/boto_apigateway.py | usage_plan_present | def usage_plan_present(name, plan_name, description=None, throttle=None, quota=None, region=None, key=None, keyid=None,
profile=None):
'''
Ensure the spcifieda usage plan with the corresponding metrics is deployed
.. versionadded:: 2017.7.0
name
name of the state
plan_name
[Required] name of the usage plan
throttle
[Optional] throttling parameters expressed as a dictionary.
If provided, at least one of the throttling parameters must be present
rateLimit
rate per second at which capacity bucket is populated
burstLimit
maximum rate allowed
quota
[Optional] quota on the number of api calls permitted by the plan.
If provided, limit and period must be present
limit
[Required] number of calls permitted per quota period
offset
[Optional] number of calls to be subtracted from the limit at the beginning of the period
period
[Required] period to which quota applies. Must be DAY, WEEK or MONTH
.. code-block:: yaml
UsagePlanPresent:
boto_apigateway.usage_plan_present:
- plan_name: my_usage_plan
- throttle:
rateLimit: 70
burstLimit: 100
- quota:
limit: 1000
offset: 0
period: DAY
- profile: my_profile
'''
func_params = locals()
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
existing = __salt__['boto_apigateway.describe_usage_plans'](name=plan_name, **common_args)
if 'error' in existing:
ret['result'] = False
ret['comment'] = 'Failed to describe existing usage plans'
return ret
if not existing['plans']:
# plan does not exist, we need to create it
if __opts__['test']:
ret['comment'] = 'a new usage plan {0} would be created'.format(plan_name)
ret['result'] = None
return ret
result = __salt__['boto_apigateway.create_usage_plan'](name=plan_name,
description=description,
throttle=throttle,
quota=quota,
**common_args)
if 'error' in result:
ret['result'] = False
ret['comment'] = 'Failed to create a usage plan {0}, {1}'.format(plan_name, result['error'])
return ret
ret['changes']['old'] = {'plan': None}
ret['comment'] = 'A new usage plan {0} has been created'.format(plan_name)
else:
# need an existing plan modified to match given value
plan = existing['plans'][0]
needs_updating = False
modifiable_params = (('throttle', ('rateLimit', 'burstLimit')), ('quota', ('limit', 'offset', 'period')))
for p, fields in modifiable_params:
for f in fields:
actual_param = {} if func_params.get(p) is None else func_params.get(p)
if plan.get(p, {}).get(f, None) != actual_param.get(f, None):
needs_updating = True
break
if not needs_updating:
ret['comment'] = 'usage plan {0} is already in a correct state'.format(plan_name)
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'a new usage plan {0} would be updated'.format(plan_name)
ret['result'] = None
return ret
result = __salt__['boto_apigateway.update_usage_plan'](plan['id'],
throttle=throttle,
quota=quota,
**common_args)
if 'error' in result:
ret['result'] = False
ret['comment'] = 'Failed to update a usage plan {0}, {1}'.format(plan_name, result['error'])
return ret
ret['changes']['old'] = {'plan': plan}
ret['comment'] = 'usage plan {0} has been updated'.format(plan_name)
newstate = __salt__['boto_apigateway.describe_usage_plans'](name=plan_name, **common_args)
if 'error' in existing:
ret['result'] = False
ret['comment'] = 'Failed to describe existing usage plans after updates'
return ret
ret['changes']['new'] = {'plan': newstate['plans'][0]}
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | python | def usage_plan_present(name, plan_name, description=None, throttle=None, quota=None, region=None, key=None, keyid=None,
profile=None):
'''
Ensure the spcifieda usage plan with the corresponding metrics is deployed
.. versionadded:: 2017.7.0
name
name of the state
plan_name
[Required] name of the usage plan
throttle
[Optional] throttling parameters expressed as a dictionary.
If provided, at least one of the throttling parameters must be present
rateLimit
rate per second at which capacity bucket is populated
burstLimit
maximum rate allowed
quota
[Optional] quota on the number of api calls permitted by the plan.
If provided, limit and period must be present
limit
[Required] number of calls permitted per quota period
offset
[Optional] number of calls to be subtracted from the limit at the beginning of the period
period
[Required] period to which quota applies. Must be DAY, WEEK or MONTH
.. code-block:: yaml
UsagePlanPresent:
boto_apigateway.usage_plan_present:
- plan_name: my_usage_plan
- throttle:
rateLimit: 70
burstLimit: 100
- quota:
limit: 1000
offset: 0
period: DAY
- profile: my_profile
'''
func_params = locals()
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
existing = __salt__['boto_apigateway.describe_usage_plans'](name=plan_name, **common_args)
if 'error' in existing:
ret['result'] = False
ret['comment'] = 'Failed to describe existing usage plans'
return ret
if not existing['plans']:
# plan does not exist, we need to create it
if __opts__['test']:
ret['comment'] = 'a new usage plan {0} would be created'.format(plan_name)
ret['result'] = None
return ret
result = __salt__['boto_apigateway.create_usage_plan'](name=plan_name,
description=description,
throttle=throttle,
quota=quota,
**common_args)
if 'error' in result:
ret['result'] = False
ret['comment'] = 'Failed to create a usage plan {0}, {1}'.format(plan_name, result['error'])
return ret
ret['changes']['old'] = {'plan': None}
ret['comment'] = 'A new usage plan {0} has been created'.format(plan_name)
else:
# need an existing plan modified to match given value
plan = existing['plans'][0]
needs_updating = False
modifiable_params = (('throttle', ('rateLimit', 'burstLimit')), ('quota', ('limit', 'offset', 'period')))
for p, fields in modifiable_params:
for f in fields:
actual_param = {} if func_params.get(p) is None else func_params.get(p)
if plan.get(p, {}).get(f, None) != actual_param.get(f, None):
needs_updating = True
break
if not needs_updating:
ret['comment'] = 'usage plan {0} is already in a correct state'.format(plan_name)
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'a new usage plan {0} would be updated'.format(plan_name)
ret['result'] = None
return ret
result = __salt__['boto_apigateway.update_usage_plan'](plan['id'],
throttle=throttle,
quota=quota,
**common_args)
if 'error' in result:
ret['result'] = False
ret['comment'] = 'Failed to update a usage plan {0}, {1}'.format(plan_name, result['error'])
return ret
ret['changes']['old'] = {'plan': plan}
ret['comment'] = 'usage plan {0} has been updated'.format(plan_name)
newstate = __salt__['boto_apigateway.describe_usage_plans'](name=plan_name, **common_args)
if 'error' in existing:
ret['result'] = False
ret['comment'] = 'Failed to describe existing usage plans after updates'
return ret
ret['changes']['new'] = {'plan': newstate['plans'][0]}
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | [
"def",
"usage_plan_present",
"(",
"name",
",",
"plan_name",
",",
"description",
"=",
"None",
",",
"throttle",
"=",
"None",
",",
"quota",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
... | Ensure the spcifieda usage plan with the corresponding metrics is deployed
.. versionadded:: 2017.7.0
name
name of the state
plan_name
[Required] name of the usage plan
throttle
[Optional] throttling parameters expressed as a dictionary.
If provided, at least one of the throttling parameters must be present
rateLimit
rate per second at which capacity bucket is populated
burstLimit
maximum rate allowed
quota
[Optional] quota on the number of api calls permitted by the plan.
If provided, limit and period must be present
limit
[Required] number of calls permitted per quota period
offset
[Optional] number of calls to be subtracted from the limit at the beginning of the period
period
[Required] period to which quota applies. Must be DAY, WEEK or MONTH
.. code-block:: yaml
UsagePlanPresent:
boto_apigateway.usage_plan_present:
- plan_name: my_usage_plan
- throttle:
rateLimit: 70
burstLimit: 100
- quota:
limit: 1000
offset: 0
period: DAY
- profile: my_profile | [
"Ensure",
"the",
"spcifieda",
"usage",
"plan",
"with",
"the",
"corresponding",
"metrics",
"is",
"deployed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1688-L1826 | train |
saltstack/salt | salt/states/boto_apigateway.py | usage_plan_absent | def usage_plan_absent(name, plan_name, region=None, key=None, keyid=None, profile=None):
'''
Ensures usage plan identified by name is no longer present
.. versionadded:: 2017.7.0
name
name of the state
plan_name
name of the plan to remove
.. code-block:: yaml
usage plan absent:
boto_apigateway.usage_plan_absent:
- plan_name: my_usage_plan
- profile: my_profile
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
existing = __salt__['boto_apigateway.describe_usage_plans'](name=plan_name, **common_args)
if 'error' in existing:
ret['result'] = False
ret['comment'] = 'Failed to describe existing usage plans'
return ret
if not existing['plans']:
ret['comment'] = 'Usage plan {0} does not exist already'.format(plan_name)
return ret
if __opts__['test']:
ret['comment'] = 'Usage plan {0} exists and would be deleted'.format(plan_name)
ret['result'] = None
return ret
plan_id = existing['plans'][0]['id']
result = __salt__['boto_apigateway.delete_usage_plan'](plan_id, **common_args)
if 'error' in result:
ret['result'] = False
ret['comment'] = 'Failed to delete usage plan {0}, {1}'.format(plan_name, result)
return ret
ret['comment'] = 'Usage plan {0} has been deleted'.format(plan_name)
ret['changes']['old'] = {'plan': existing['plans'][0]}
ret['changes']['new'] = {'plan': None}
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | python | def usage_plan_absent(name, plan_name, region=None, key=None, keyid=None, profile=None):
'''
Ensures usage plan identified by name is no longer present
.. versionadded:: 2017.7.0
name
name of the state
plan_name
name of the plan to remove
.. code-block:: yaml
usage plan absent:
boto_apigateway.usage_plan_absent:
- plan_name: my_usage_plan
- profile: my_profile
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
existing = __salt__['boto_apigateway.describe_usage_plans'](name=plan_name, **common_args)
if 'error' in existing:
ret['result'] = False
ret['comment'] = 'Failed to describe existing usage plans'
return ret
if not existing['plans']:
ret['comment'] = 'Usage plan {0} does not exist already'.format(plan_name)
return ret
if __opts__['test']:
ret['comment'] = 'Usage plan {0} exists and would be deleted'.format(plan_name)
ret['result'] = None
return ret
plan_id = existing['plans'][0]['id']
result = __salt__['boto_apigateway.delete_usage_plan'](plan_id, **common_args)
if 'error' in result:
ret['result'] = False
ret['comment'] = 'Failed to delete usage plan {0}, {1}'.format(plan_name, result)
return ret
ret['comment'] = 'Usage plan {0} has been deleted'.format(plan_name)
ret['changes']['old'] = {'plan': existing['plans'][0]}
ret['changes']['new'] = {'plan': None}
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | [
"def",
"usage_plan_absent",
"(",
"name",
",",
"plan_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
... | Ensures usage plan identified by name is no longer present
.. versionadded:: 2017.7.0
name
name of the state
plan_name
name of the plan to remove
.. code-block:: yaml
usage plan absent:
boto_apigateway.usage_plan_absent:
- plan_name: my_usage_plan
- profile: my_profile | [
"Ensures",
"usage",
"plan",
"identified",
"by",
"name",
"is",
"no",
"longer",
"present"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1829-L1892 | train |
saltstack/salt | salt/states/boto_apigateway.py | usage_plan_association_present | def usage_plan_association_present(name, plan_name, api_stages, region=None, key=None, keyid=None, profile=None):
'''
Ensures usage plan identified by name is added to provided api_stages
.. versionadded:: 2017.7.0
name
name of the state
plan_name
name of the plan to use
api_stages
list of dictionaries, where each dictionary consists of the following keys:
apiId
apiId of the api to attach usage plan to
stage
stage name of the api to attach usage plan to
.. code-block:: yaml
UsagePlanAssociationPresent:
boto_apigateway.usage_plan_association_present:
- plan_name: my_plan
- api_stages:
- apiId: 9kb0404ec0
stage: my_stage
- apiId: l9v7o2aj90
stage: my_stage
- profile: my_profile
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
existing = __salt__['boto_apigateway.describe_usage_plans'](name=plan_name, **common_args)
if 'error' in existing:
ret['result'] = False
ret['comment'] = 'Failed to describe existing usage plans'
return ret
if not existing['plans']:
ret['comment'] = 'Usage plan {0} does not exist'.format(plan_name)
ret['result'] = False
return ret
if len(existing['plans']) != 1:
ret['comment'] = 'There are multiple usage plans with the same name - it is not supported'
ret['result'] = False
return ret
plan = existing['plans'][0]
plan_id = plan['id']
plan_stages = plan.get('apiStages', [])
stages_to_add = []
for api in api_stages:
if api not in plan_stages:
stages_to_add.append(api)
if not stages_to_add:
ret['comment'] = 'Usage plan is already asssociated to all api stages'
return ret
result = __salt__['boto_apigateway.attach_usage_plan_to_apis'](plan_id, stages_to_add, **common_args)
if 'error' in result:
ret['comment'] = 'Failed to associate a usage plan {0} to the apis {1}, {2}'.format(plan_name,
stages_to_add,
result['error'])
ret['result'] = False
return ret
ret['comment'] = 'successfully associated usage plan to apis'
ret['changes']['old'] = plan_stages
ret['changes']['new'] = result.get('result', {}).get('apiStages', [])
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | python | def usage_plan_association_present(name, plan_name, api_stages, region=None, key=None, keyid=None, profile=None):
'''
Ensures usage plan identified by name is added to provided api_stages
.. versionadded:: 2017.7.0
name
name of the state
plan_name
name of the plan to use
api_stages
list of dictionaries, where each dictionary consists of the following keys:
apiId
apiId of the api to attach usage plan to
stage
stage name of the api to attach usage plan to
.. code-block:: yaml
UsagePlanAssociationPresent:
boto_apigateway.usage_plan_association_present:
- plan_name: my_plan
- api_stages:
- apiId: 9kb0404ec0
stage: my_stage
- apiId: l9v7o2aj90
stage: my_stage
- profile: my_profile
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
try:
common_args = dict([('region', region),
('key', key),
('keyid', keyid),
('profile', profile)])
existing = __salt__['boto_apigateway.describe_usage_plans'](name=plan_name, **common_args)
if 'error' in existing:
ret['result'] = False
ret['comment'] = 'Failed to describe existing usage plans'
return ret
if not existing['plans']:
ret['comment'] = 'Usage plan {0} does not exist'.format(plan_name)
ret['result'] = False
return ret
if len(existing['plans']) != 1:
ret['comment'] = 'There are multiple usage plans with the same name - it is not supported'
ret['result'] = False
return ret
plan = existing['plans'][0]
plan_id = plan['id']
plan_stages = plan.get('apiStages', [])
stages_to_add = []
for api in api_stages:
if api not in plan_stages:
stages_to_add.append(api)
if not stages_to_add:
ret['comment'] = 'Usage plan is already asssociated to all api stages'
return ret
result = __salt__['boto_apigateway.attach_usage_plan_to_apis'](plan_id, stages_to_add, **common_args)
if 'error' in result:
ret['comment'] = 'Failed to associate a usage plan {0} to the apis {1}, {2}'.format(plan_name,
stages_to_add,
result['error'])
ret['result'] = False
return ret
ret['comment'] = 'successfully associated usage plan to apis'
ret['changes']['old'] = plan_stages
ret['changes']['new'] = result.get('result', {}).get('apiStages', [])
except (ValueError, IOError) as e:
ret['result'] = False
ret['comment'] = '{0}'.format(e.args)
return ret | [
"def",
"usage_plan_association_present",
"(",
"name",
",",
"plan_name",
",",
"api_stages",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",... | Ensures usage plan identified by name is added to provided api_stages
.. versionadded:: 2017.7.0
name
name of the state
plan_name
name of the plan to use
api_stages
list of dictionaries, where each dictionary consists of the following keys:
apiId
apiId of the api to attach usage plan to
stage
stage name of the api to attach usage plan to
.. code-block:: yaml
UsagePlanAssociationPresent:
boto_apigateway.usage_plan_association_present:
- plan_name: my_plan
- api_stages:
- apiId: 9kb0404ec0
stage: my_stage
- apiId: l9v7o2aj90
stage: my_stage
- profile: my_profile | [
"Ensures",
"usage",
"plan",
"identified",
"by",
"name",
"is",
"added",
"to",
"provided",
"api_stages"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1895-L1985 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger._validate_error_response_model | def _validate_error_response_model(self, paths, mods):
'''
Helper function to help validate the convention established in the swagger file on how
to handle response code mapping/integration
'''
for path, ops in paths:
for opname, opobj in six.iteritems(ops):
if opname not in _Swagger.SWAGGER_OPERATION_NAMES:
continue
if 'responses' not in opobj:
raise ValueError('missing mandatory responses field in path item object')
for rescode, resobj in six.iteritems(opobj.get('responses')):
if not self._is_http_error_rescode(str(rescode)): # future lint: disable=blacklisted-function
continue
# only check for response code from 400-599
if 'schema' not in resobj:
raise ValueError('missing schema field in path {0}, '
'op {1}, response {2}'.format(path, opname, rescode))
schemaobj = resobj.get('schema')
if '$ref' not in schemaobj:
raise ValueError('missing $ref field under schema in '
'path {0}, op {1}, response {2}'.format(path, opname, rescode))
schemaobjref = schemaobj.get('$ref', '/')
modelname = schemaobjref.split('/')[-1]
if modelname not in mods:
raise ValueError('model schema {0} reference not found '
'under /definitions'.format(schemaobjref))
model = mods.get(modelname)
if model.get('type') != 'object':
raise ValueError('model schema {0} must be type object'.format(modelname))
if 'properties' not in model:
raise ValueError('model schema {0} must have properties fields'.format(modelname))
modelprops = model.get('properties')
if 'errorMessage' not in modelprops:
raise ValueError('model schema {0} must have errorMessage as a property to '
'match AWS convention. If pattern is not set, .+ will '
'be used'.format(modelname)) | python | def _validate_error_response_model(self, paths, mods):
'''
Helper function to help validate the convention established in the swagger file on how
to handle response code mapping/integration
'''
for path, ops in paths:
for opname, opobj in six.iteritems(ops):
if opname not in _Swagger.SWAGGER_OPERATION_NAMES:
continue
if 'responses' not in opobj:
raise ValueError('missing mandatory responses field in path item object')
for rescode, resobj in six.iteritems(opobj.get('responses')):
if not self._is_http_error_rescode(str(rescode)): # future lint: disable=blacklisted-function
continue
# only check for response code from 400-599
if 'schema' not in resobj:
raise ValueError('missing schema field in path {0}, '
'op {1}, response {2}'.format(path, opname, rescode))
schemaobj = resobj.get('schema')
if '$ref' not in schemaobj:
raise ValueError('missing $ref field under schema in '
'path {0}, op {1}, response {2}'.format(path, opname, rescode))
schemaobjref = schemaobj.get('$ref', '/')
modelname = schemaobjref.split('/')[-1]
if modelname not in mods:
raise ValueError('model schema {0} reference not found '
'under /definitions'.format(schemaobjref))
model = mods.get(modelname)
if model.get('type') != 'object':
raise ValueError('model schema {0} must be type object'.format(modelname))
if 'properties' not in model:
raise ValueError('model schema {0} must have properties fields'.format(modelname))
modelprops = model.get('properties')
if 'errorMessage' not in modelprops:
raise ValueError('model schema {0} must have errorMessage as a property to '
'match AWS convention. If pattern is not set, .+ will '
'be used'.format(modelname)) | [
"def",
"_validate_error_response_model",
"(",
"self",
",",
"paths",
",",
"mods",
")",
":",
"for",
"path",
",",
"ops",
"in",
"paths",
":",
"for",
"opname",
",",
"opobj",
"in",
"six",
".",
"iteritems",
"(",
"ops",
")",
":",
"if",
"opname",
"not",
"in",
... | Helper function to help validate the convention established in the swagger file on how
to handle response code mapping/integration | [
"Helper",
"function",
"to",
"help",
"validate",
"the",
"convention",
"established",
"in",
"the",
"swagger",
"file",
"on",
"how",
"to",
"handle",
"response",
"code",
"mapping",
"/",
"integration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L754-L796 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger._validate_lambda_funcname_format | def _validate_lambda_funcname_format(self):
'''
Checks if the lambda function name format contains only known elements
:return: True on success, ValueError raised on error
'''
try:
if self._lambda_funcname_format:
known_kwargs = dict(stage='',
api='',
resource='',
method='')
self._lambda_funcname_format.format(**known_kwargs)
return True
except Exception:
raise ValueError('Invalid lambda_funcname_format {0}. Please review '
'documentation for known substitutable keys'.format(self._lambda_funcname_format)) | python | def _validate_lambda_funcname_format(self):
'''
Checks if the lambda function name format contains only known elements
:return: True on success, ValueError raised on error
'''
try:
if self._lambda_funcname_format:
known_kwargs = dict(stage='',
api='',
resource='',
method='')
self._lambda_funcname_format.format(**known_kwargs)
return True
except Exception:
raise ValueError('Invalid lambda_funcname_format {0}. Please review '
'documentation for known substitutable keys'.format(self._lambda_funcname_format)) | [
"def",
"_validate_lambda_funcname_format",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_lambda_funcname_format",
":",
"known_kwargs",
"=",
"dict",
"(",
"stage",
"=",
"''",
",",
"api",
"=",
"''",
",",
"resource",
"=",
"''",
",",
"method",
"=",
... | Checks if the lambda function name format contains only known elements
:return: True on success, ValueError raised on error | [
"Checks",
"if",
"the",
"lambda",
"function",
"name",
"format",
"contains",
"only",
"known",
"elements",
":",
"return",
":",
"True",
"on",
"success",
"ValueError",
"raised",
"on",
"error"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L798-L813 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger._validate_swagger_file | def _validate_swagger_file(self):
'''
High level check/validation of the input swagger file based on
https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
This is not a full schema compliance check, but rather make sure that the input file (YAML or
JSON) can be read into a dictionary, and we check for the content of the Swagger Object for version
and info.
'''
# check for any invalid fields for Swagger Object V2
for field in self._cfg:
if (field not in _Swagger.SWAGGER_OBJ_V2_FIELDS and
not _Swagger.VENDOR_EXT_PATTERN.match(field)):
raise ValueError('Invalid Swagger Object Field: {0}'.format(field))
# check for Required Swagger fields by Saltstack boto apigateway state
for field in _Swagger.SWAGGER_OBJ_V2_FIELDS_REQUIRED:
if field not in self._cfg:
raise ValueError('Missing Swagger Object Field: {0}'.format(field))
# check for Swagger Version
self._swagger_version = self._cfg.get('swagger')
if self._swagger_version not in _Swagger.SWAGGER_VERSIONS_SUPPORTED:
raise ValueError('Unsupported Swagger version: {0},'
'Supported versions are {1}'.format(self._swagger_version,
_Swagger.SWAGGER_VERSIONS_SUPPORTED))
log.info(type(self._models))
self._validate_error_response_model(self.paths, self._models()) | python | def _validate_swagger_file(self):
'''
High level check/validation of the input swagger file based on
https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
This is not a full schema compliance check, but rather make sure that the input file (YAML or
JSON) can be read into a dictionary, and we check for the content of the Swagger Object for version
and info.
'''
# check for any invalid fields for Swagger Object V2
for field in self._cfg:
if (field not in _Swagger.SWAGGER_OBJ_V2_FIELDS and
not _Swagger.VENDOR_EXT_PATTERN.match(field)):
raise ValueError('Invalid Swagger Object Field: {0}'.format(field))
# check for Required Swagger fields by Saltstack boto apigateway state
for field in _Swagger.SWAGGER_OBJ_V2_FIELDS_REQUIRED:
if field not in self._cfg:
raise ValueError('Missing Swagger Object Field: {0}'.format(field))
# check for Swagger Version
self._swagger_version = self._cfg.get('swagger')
if self._swagger_version not in _Swagger.SWAGGER_VERSIONS_SUPPORTED:
raise ValueError('Unsupported Swagger version: {0},'
'Supported versions are {1}'.format(self._swagger_version,
_Swagger.SWAGGER_VERSIONS_SUPPORTED))
log.info(type(self._models))
self._validate_error_response_model(self.paths, self._models()) | [
"def",
"_validate_swagger_file",
"(",
"self",
")",
":",
"# check for any invalid fields for Swagger Object V2",
"for",
"field",
"in",
"self",
".",
"_cfg",
":",
"if",
"(",
"field",
"not",
"in",
"_Swagger",
".",
"SWAGGER_OBJ_V2_FIELDS",
"and",
"not",
"_Swagger",
".",
... | High level check/validation of the input swagger file based on
https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
This is not a full schema compliance check, but rather make sure that the input file (YAML or
JSON) can be read into a dictionary, and we check for the content of the Swagger Object for version
and info. | [
"High",
"level",
"check",
"/",
"validation",
"of",
"the",
"input",
"swagger",
"file",
"based",
"on",
"https",
":",
"//",
"github",
".",
"com",
"/",
"swagger",
"-",
"api",
"/",
"swagger",
"-",
"spec",
"/",
"blob",
"/",
"master",
"/",
"versions",
"/",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L815-L844 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger.models | def models(self):
'''
generator to return the tuple of model and its schema to create on aws.
'''
model_dict = self._build_all_dependencies()
while True:
model = self._get_model_without_dependencies(model_dict)
if not model:
break
yield (model, self._models().get(model)) | python | def models(self):
'''
generator to return the tuple of model and its schema to create on aws.
'''
model_dict = self._build_all_dependencies()
while True:
model = self._get_model_without_dependencies(model_dict)
if not model:
break
yield (model, self._models().get(model)) | [
"def",
"models",
"(",
"self",
")",
":",
"model_dict",
"=",
"self",
".",
"_build_all_dependencies",
"(",
")",
"while",
"True",
":",
"model",
"=",
"self",
".",
"_get_model_without_dependencies",
"(",
"model_dict",
")",
"if",
"not",
"model",
":",
"break",
"yiel... | generator to return the tuple of model and its schema to create on aws. | [
"generator",
"to",
"return",
"the",
"tuple",
"of",
"model",
"and",
"its",
"schema",
"to",
"create",
"on",
"aws",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L898-L907 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger.paths | def paths(self):
'''
returns an iterator for the relative resource paths specified in the swagger file
'''
paths = self._cfg.get('paths')
if not paths:
raise ValueError('Paths Object has no values, You need to define them in your swagger file')
for path in paths:
if not path.startswith('/'):
raise ValueError('Path object {0} should start with /. Please fix it'.format(path))
return six.iteritems(paths) | python | def paths(self):
'''
returns an iterator for the relative resource paths specified in the swagger file
'''
paths = self._cfg.get('paths')
if not paths:
raise ValueError('Paths Object has no values, You need to define them in your swagger file')
for path in paths:
if not path.startswith('/'):
raise ValueError('Path object {0} should start with /. Please fix it'.format(path))
return six.iteritems(paths) | [
"def",
"paths",
"(",
"self",
")",
":",
"paths",
"=",
"self",
".",
"_cfg",
".",
"get",
"(",
"'paths'",
")",
"if",
"not",
"paths",
":",
"raise",
"ValueError",
"(",
"'Paths Object has no values, You need to define them in your swagger file'",
")",
"for",
"path",
"i... | returns an iterator for the relative resource paths specified in the swagger file | [
"returns",
"an",
"iterator",
"for",
"the",
"relative",
"resource",
"paths",
"specified",
"in",
"the",
"swagger",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L910-L920 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger.deployment_label | def deployment_label(self):
'''
this property returns the deployment label dictionary (mainly used by
stage description)
'''
label = dict()
label['swagger_info_object'] = self.info
label['api_name'] = self.rest_api_name
label['swagger_file'] = os.path.basename(self._swagger_file)
label['swagger_file_md5sum'] = self.md5_filehash
return label | python | def deployment_label(self):
'''
this property returns the deployment label dictionary (mainly used by
stage description)
'''
label = dict()
label['swagger_info_object'] = self.info
label['api_name'] = self.rest_api_name
label['swagger_file'] = os.path.basename(self._swagger_file)
label['swagger_file_md5sum'] = self.md5_filehash
return label | [
"def",
"deployment_label",
"(",
"self",
")",
":",
"label",
"=",
"dict",
"(",
")",
"label",
"[",
"'swagger_info_object'",
"]",
"=",
"self",
".",
"info",
"label",
"[",
"'api_name'",
"]",
"=",
"self",
".",
"rest_api_name",
"label",
"[",
"'swagger_file'",
"]",... | this property returns the deployment label dictionary (mainly used by
stage description) | [
"this",
"property",
"returns",
"the",
"deployment",
"label",
"dictionary",
"(",
"mainly",
"used",
"by",
"stage",
"description",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L953-L965 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger._one_or_more_stages_remain | def _one_or_more_stages_remain(self, deploymentId):
'''
Helper function to find whether there are other stages still associated with a deployment
'''
stages = __salt__['boto_apigateway.describe_api_stages'](restApiId=self.restApiId,
deploymentId=deploymentId,
**self._common_aws_args).get('stages')
return bool(stages) | python | def _one_or_more_stages_remain(self, deploymentId):
'''
Helper function to find whether there are other stages still associated with a deployment
'''
stages = __salt__['boto_apigateway.describe_api_stages'](restApiId=self.restApiId,
deploymentId=deploymentId,
**self._common_aws_args).get('stages')
return bool(stages) | [
"def",
"_one_or_more_stages_remain",
"(",
"self",
",",
"deploymentId",
")",
":",
"stages",
"=",
"__salt__",
"[",
"'boto_apigateway.describe_api_stages'",
"]",
"(",
"restApiId",
"=",
"self",
".",
"restApiId",
",",
"deploymentId",
"=",
"deploymentId",
",",
"*",
"*",... | Helper function to find whether there are other stages still associated with a deployment | [
"Helper",
"function",
"to",
"find",
"whether",
"there",
"are",
"other",
"stages",
"still",
"associated",
"with",
"a",
"deployment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L968-L975 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger.no_more_deployments_remain | def no_more_deployments_remain(self):
'''
Helper function to find whether there are deployments left with stages associated
'''
no_more_deployments = True
deployments = __salt__['boto_apigateway.describe_api_deployments'](restApiId=self.restApiId,
**self._common_aws_args).get('deployments')
if deployments:
for deployment in deployments:
deploymentId = deployment.get('id')
stages = __salt__['boto_apigateway.describe_api_stages'](restApiId=self.restApiId,
deploymentId=deploymentId,
**self._common_aws_args).get('stages')
if stages:
no_more_deployments = False
break
return no_more_deployments | python | def no_more_deployments_remain(self):
'''
Helper function to find whether there are deployments left with stages associated
'''
no_more_deployments = True
deployments = __salt__['boto_apigateway.describe_api_deployments'](restApiId=self.restApiId,
**self._common_aws_args).get('deployments')
if deployments:
for deployment in deployments:
deploymentId = deployment.get('id')
stages = __salt__['boto_apigateway.describe_api_stages'](restApiId=self.restApiId,
deploymentId=deploymentId,
**self._common_aws_args).get('stages')
if stages:
no_more_deployments = False
break
return no_more_deployments | [
"def",
"no_more_deployments_remain",
"(",
"self",
")",
":",
"no_more_deployments",
"=",
"True",
"deployments",
"=",
"__salt__",
"[",
"'boto_apigateway.describe_api_deployments'",
"]",
"(",
"restApiId",
"=",
"self",
".",
"restApiId",
",",
"*",
"*",
"self",
".",
"_c... | Helper function to find whether there are deployments left with stages associated | [
"Helper",
"function",
"to",
"find",
"whether",
"there",
"are",
"deployments",
"left",
"with",
"stages",
"associated"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L977-L994 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger._get_current_deployment_id | def _get_current_deployment_id(self):
'''
Helper method to find the deployment id that the stage name is currently assocaited with.
'''
deploymentId = ''
stage = __salt__['boto_apigateway.describe_api_stage'](restApiId=self.restApiId,
stageName=self._stage_name,
**self._common_aws_args).get('stage')
if stage:
deploymentId = stage.get('deploymentId')
return deploymentId | python | def _get_current_deployment_id(self):
'''
Helper method to find the deployment id that the stage name is currently assocaited with.
'''
deploymentId = ''
stage = __salt__['boto_apigateway.describe_api_stage'](restApiId=self.restApiId,
stageName=self._stage_name,
**self._common_aws_args).get('stage')
if stage:
deploymentId = stage.get('deploymentId')
return deploymentId | [
"def",
"_get_current_deployment_id",
"(",
"self",
")",
":",
"deploymentId",
"=",
"''",
"stage",
"=",
"__salt__",
"[",
"'boto_apigateway.describe_api_stage'",
"]",
"(",
"restApiId",
"=",
"self",
".",
"restApiId",
",",
"stageName",
"=",
"self",
".",
"_stage_name",
... | Helper method to find the deployment id that the stage name is currently assocaited with. | [
"Helper",
"method",
"to",
"find",
"the",
"deployment",
"id",
"that",
"the",
"stage",
"name",
"is",
"currently",
"assocaited",
"with",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L996-L1006 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger._get_current_deployment_label | def _get_current_deployment_label(self):
'''
Helper method to find the deployment label that the stage_name is currently associated with.
'''
deploymentId = self._get_current_deployment_id()
deployment = __salt__['boto_apigateway.describe_api_deployment'](restApiId=self.restApiId,
deploymentId=deploymentId,
**self._common_aws_args).get('deployment')
if deployment:
return deployment.get('description')
return None | python | def _get_current_deployment_label(self):
'''
Helper method to find the deployment label that the stage_name is currently associated with.
'''
deploymentId = self._get_current_deployment_id()
deployment = __salt__['boto_apigateway.describe_api_deployment'](restApiId=self.restApiId,
deploymentId=deploymentId,
**self._common_aws_args).get('deployment')
if deployment:
return deployment.get('description')
return None | [
"def",
"_get_current_deployment_label",
"(",
"self",
")",
":",
"deploymentId",
"=",
"self",
".",
"_get_current_deployment_id",
"(",
")",
"deployment",
"=",
"__salt__",
"[",
"'boto_apigateway.describe_api_deployment'",
"]",
"(",
"restApiId",
"=",
"self",
".",
"restApiI... | Helper method to find the deployment label that the stage_name is currently associated with. | [
"Helper",
"method",
"to",
"find",
"the",
"deployment",
"label",
"that",
"the",
"stage_name",
"is",
"currently",
"associated",
"with",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1008-L1018 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger._get_desired_deployment_id | def _get_desired_deployment_id(self):
'''
Helper method to return the deployment id matching the desired deployment label for
this Swagger object based on the given api_name, swagger_file
'''
deployments = __salt__['boto_apigateway.describe_api_deployments'](restApiId=self.restApiId,
**self._common_aws_args).get('deployments')
if deployments:
for deployment in deployments:
if deployment.get('description') == self.deployment_label_json:
return deployment.get('id')
return '' | python | def _get_desired_deployment_id(self):
'''
Helper method to return the deployment id matching the desired deployment label for
this Swagger object based on the given api_name, swagger_file
'''
deployments = __salt__['boto_apigateway.describe_api_deployments'](restApiId=self.restApiId,
**self._common_aws_args).get('deployments')
if deployments:
for deployment in deployments:
if deployment.get('description') == self.deployment_label_json:
return deployment.get('id')
return '' | [
"def",
"_get_desired_deployment_id",
"(",
"self",
")",
":",
"deployments",
"=",
"__salt__",
"[",
"'boto_apigateway.describe_api_deployments'",
"]",
"(",
"restApiId",
"=",
"self",
".",
"restApiId",
",",
"*",
"*",
"self",
".",
"_common_aws_args",
")",
".",
"get",
... | Helper method to return the deployment id matching the desired deployment label for
this Swagger object based on the given api_name, swagger_file | [
"Helper",
"method",
"to",
"return",
"the",
"deployment",
"id",
"matching",
"the",
"desired",
"deployment",
"label",
"for",
"this",
"Swagger",
"object",
"based",
"on",
"the",
"given",
"api_name",
"swagger_file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1020-L1031 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger.overwrite_stage_variables | def overwrite_stage_variables(self, ret, stage_variables):
'''
overwrite the given stage_name's stage variables with the given stage_variables
'''
res = __salt__['boto_apigateway.overwrite_api_stage_variables'](restApiId=self.restApiId,
stageName=self._stage_name,
variables=stage_variables,
**self._common_aws_args)
if not res.get('overwrite'):
ret['result'] = False
ret['abort'] = True
ret['comment'] = res.get('error')
else:
ret = _log_changes(ret,
'overwrite_stage_variables',
res.get('stage'))
return ret | python | def overwrite_stage_variables(self, ret, stage_variables):
'''
overwrite the given stage_name's stage variables with the given stage_variables
'''
res = __salt__['boto_apigateway.overwrite_api_stage_variables'](restApiId=self.restApiId,
stageName=self._stage_name,
variables=stage_variables,
**self._common_aws_args)
if not res.get('overwrite'):
ret['result'] = False
ret['abort'] = True
ret['comment'] = res.get('error')
else:
ret = _log_changes(ret,
'overwrite_stage_variables',
res.get('stage'))
return ret | [
"def",
"overwrite_stage_variables",
"(",
"self",
",",
"ret",
",",
"stage_variables",
")",
":",
"res",
"=",
"__salt__",
"[",
"'boto_apigateway.overwrite_api_stage_variables'",
"]",
"(",
"restApiId",
"=",
"self",
".",
"restApiId",
",",
"stageName",
"=",
"self",
".",... | overwrite the given stage_name's stage variables with the given stage_variables | [
"overwrite",
"the",
"given",
"stage_name",
"s",
"stage",
"variables",
"with",
"the",
"given",
"stage_variables"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1033-L1050 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger._set_current_deployment | def _set_current_deployment(self, stage_desc_json, stage_variables):
'''
Helper method to associate the stage_name to the given deploymentId and make this current
'''
stage = __salt__['boto_apigateway.describe_api_stage'](restApiId=self.restApiId,
stageName=self._stage_name,
**self._common_aws_args).get('stage')
if not stage:
stage = __salt__['boto_apigateway.create_api_stage'](restApiId=self.restApiId,
stageName=self._stage_name,
deploymentId=self._deploymentId,
description=stage_desc_json,
variables=stage_variables,
**self._common_aws_args)
if not stage.get('stage'):
return {'set': False, 'error': stage.get('error')}
else:
# overwrite the stage variables
overwrite = __salt__['boto_apigateway.overwrite_api_stage_variables'](restApiId=self.restApiId,
stageName=self._stage_name,
variables=stage_variables,
**self._common_aws_args)
if not overwrite.get('stage'):
return {'set': False, 'error': overwrite.get('error')}
return __salt__['boto_apigateway.activate_api_deployment'](restApiId=self.restApiId,
stageName=self._stage_name,
deploymentId=self._deploymentId,
**self._common_aws_args) | python | def _set_current_deployment(self, stage_desc_json, stage_variables):
'''
Helper method to associate the stage_name to the given deploymentId and make this current
'''
stage = __salt__['boto_apigateway.describe_api_stage'](restApiId=self.restApiId,
stageName=self._stage_name,
**self._common_aws_args).get('stage')
if not stage:
stage = __salt__['boto_apigateway.create_api_stage'](restApiId=self.restApiId,
stageName=self._stage_name,
deploymentId=self._deploymentId,
description=stage_desc_json,
variables=stage_variables,
**self._common_aws_args)
if not stage.get('stage'):
return {'set': False, 'error': stage.get('error')}
else:
# overwrite the stage variables
overwrite = __salt__['boto_apigateway.overwrite_api_stage_variables'](restApiId=self.restApiId,
stageName=self._stage_name,
variables=stage_variables,
**self._common_aws_args)
if not overwrite.get('stage'):
return {'set': False, 'error': overwrite.get('error')}
return __salt__['boto_apigateway.activate_api_deployment'](restApiId=self.restApiId,
stageName=self._stage_name,
deploymentId=self._deploymentId,
**self._common_aws_args) | [
"def",
"_set_current_deployment",
"(",
"self",
",",
"stage_desc_json",
",",
"stage_variables",
")",
":",
"stage",
"=",
"__salt__",
"[",
"'boto_apigateway.describe_api_stage'",
"]",
"(",
"restApiId",
"=",
"self",
".",
"restApiId",
",",
"stageName",
"=",
"self",
"."... | Helper method to associate the stage_name to the given deploymentId and make this current | [
"Helper",
"method",
"to",
"associate",
"the",
"stage_name",
"to",
"the",
"given",
"deploymentId",
"and",
"make",
"this",
"current"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1052-L1080 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger._resolve_api_id | def _resolve_api_id(self):
'''
returns an Api Id that matches the given api_name and the hardcoded _Swagger.AWS_API_DESCRIPTION
as the api description
'''
apis = __salt__['boto_apigateway.describe_apis'](name=self.rest_api_name,
description=_Swagger.AWS_API_DESCRIPTION,
**self._common_aws_args).get('restapi')
if apis:
if len(apis) == 1:
self.restApiId = apis[0].get('id')
else:
raise ValueError('Multiple APIs matching given name {0} and '
'description {1}'.format(self.rest_api_name, self.info_json)) | python | def _resolve_api_id(self):
'''
returns an Api Id that matches the given api_name and the hardcoded _Swagger.AWS_API_DESCRIPTION
as the api description
'''
apis = __salt__['boto_apigateway.describe_apis'](name=self.rest_api_name,
description=_Swagger.AWS_API_DESCRIPTION,
**self._common_aws_args).get('restapi')
if apis:
if len(apis) == 1:
self.restApiId = apis[0].get('id')
else:
raise ValueError('Multiple APIs matching given name {0} and '
'description {1}'.format(self.rest_api_name, self.info_json)) | [
"def",
"_resolve_api_id",
"(",
"self",
")",
":",
"apis",
"=",
"__salt__",
"[",
"'boto_apigateway.describe_apis'",
"]",
"(",
"name",
"=",
"self",
".",
"rest_api_name",
",",
"description",
"=",
"_Swagger",
".",
"AWS_API_DESCRIPTION",
",",
"*",
"*",
"self",
".",
... | returns an Api Id that matches the given api_name and the hardcoded _Swagger.AWS_API_DESCRIPTION
as the api description | [
"returns",
"an",
"Api",
"Id",
"that",
"matches",
"the",
"given",
"api_name",
"and",
"the",
"hardcoded",
"_Swagger",
".",
"AWS_API_DESCRIPTION",
"as",
"the",
"api",
"description"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1082-L1095 | train |
saltstack/salt | salt/states/boto_apigateway.py | _Swagger.delete_stage | def delete_stage(self, ret):
'''
Method to delete the given stage_name. If the current deployment tied to the given
stage_name has no other stages associated with it, the deployment will be removed
as well
'''
deploymentId = self._get_current_deployment_id()
if deploymentId:
result = __salt__['boto_apigateway.delete_api_stage'](restApiId=self.restApiId,
stageName=self._stage_name,
**self._common_aws_args)
if not result.get('deleted'):
ret['abort'] = True
ret['result'] = False
ret['comment'] = 'delete_stage delete_api_stage, {0}'.format(result.get('error'))
else:
# check if it is safe to delete the deployment as well.
if not self._one_or_more_stages_remain(deploymentId):
result = __salt__['boto_apigateway.delete_api_deployment'](restApiId=self.restApiId,
deploymentId=deploymentId,
**self._common_aws_args)
if not result.get('deleted'):
ret['abort'] = True
ret['result'] = False
ret['comment'] = 'delete_stage delete_api_deployment, {0}'.format(result.get('error'))
else:
ret['comment'] = 'stage {0} has been deleted.\n'.format(self._stage_name)
else:
# no matching stage_name/deployment found
ret['comment'] = 'stage {0} does not exist'.format(self._stage_name)
return ret | python | def delete_stage(self, ret):
'''
Method to delete the given stage_name. If the current deployment tied to the given
stage_name has no other stages associated with it, the deployment will be removed
as well
'''
deploymentId = self._get_current_deployment_id()
if deploymentId:
result = __salt__['boto_apigateway.delete_api_stage'](restApiId=self.restApiId,
stageName=self._stage_name,
**self._common_aws_args)
if not result.get('deleted'):
ret['abort'] = True
ret['result'] = False
ret['comment'] = 'delete_stage delete_api_stage, {0}'.format(result.get('error'))
else:
# check if it is safe to delete the deployment as well.
if not self._one_or_more_stages_remain(deploymentId):
result = __salt__['boto_apigateway.delete_api_deployment'](restApiId=self.restApiId,
deploymentId=deploymentId,
**self._common_aws_args)
if not result.get('deleted'):
ret['abort'] = True
ret['result'] = False
ret['comment'] = 'delete_stage delete_api_deployment, {0}'.format(result.get('error'))
else:
ret['comment'] = 'stage {0} has been deleted.\n'.format(self._stage_name)
else:
# no matching stage_name/deployment found
ret['comment'] = 'stage {0} does not exist'.format(self._stage_name)
return ret | [
"def",
"delete_stage",
"(",
"self",
",",
"ret",
")",
":",
"deploymentId",
"=",
"self",
".",
"_get_current_deployment_id",
"(",
")",
"if",
"deploymentId",
":",
"result",
"=",
"__salt__",
"[",
"'boto_apigateway.delete_api_stage'",
"]",
"(",
"restApiId",
"=",
"self... | Method to delete the given stage_name. If the current deployment tied to the given
stage_name has no other stages associated with it, the deployment will be removed
as well | [
"Method",
"to",
"delete",
"the",
"given",
"stage_name",
".",
"If",
"the",
"current",
"deployment",
"tied",
"to",
"the",
"given",
"stage_name",
"has",
"no",
"other",
"stages",
"associated",
"with",
"it",
"the",
"deployment",
"will",
"be",
"removed",
"as",
"we... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1097-L1128 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.