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/states/lxd_profile.py | present | def present(name, description=None, config=None, devices=None,
remote_addr=None, cert=None, key=None, verify_cert=True):
'''
Creates or updates LXD profiles
name :
The name of the profile to create/update
description :
A description string
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
A device dict or None (None = unset).
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
See the `lxd-docs`_ for the details about the config and devices dicts.
See the `requests-docs` for the SSL stuff.
.. _lxd-docs: https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-10
.. _requests-docs: http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification # noqa
'''
ret = {
'name': name,
'description': description,
'config': config,
'devices': devices,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
profile = None
try:
profile = __salt__['lxd.profile_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
pass
if description is None:
description = six.text_type()
if profile is None:
if __opts__['test']:
# Test is on, just return that we would create the profile
msg = 'Would create the profile "{0}"'.format(name)
ret['changes'] = {'created': msg}
return _unchanged(ret, msg)
# Create the profile
try:
__salt__['lxd.profile_create'](
name,
config,
devices,
description,
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = 'Profile "{0}" has been created'.format(name)
ret['changes'] = {'created': msg}
return _success(ret, msg)
config, devices = __salt__['lxd.normalize_input_values'](
config,
devices
)
#
# Description change
#
if six.text_type(profile.description) != six.text_type(description):
ret['changes']['description'] = (
'Description changed, from "{0}" to "{1}".'
).format(profile.description, description)
profile.description = description
changes = __salt__['lxd.sync_config_devices'](
profile, config, devices, __opts__['test']
)
ret['changes'].update(changes)
if not ret['changes']:
return _success(ret, 'No changes')
if __opts__['test']:
return _unchanged(
ret,
'Profile "{0}" would get changed.'.format(name)
)
try:
__salt__['lxd.pylxd_save_object'](profile)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
return _success(ret, '{0} changes'.format(len(ret['changes'].keys()))) | python | def present(name, description=None, config=None, devices=None,
remote_addr=None, cert=None, key=None, verify_cert=True):
'''
Creates or updates LXD profiles
name :
The name of the profile to create/update
description :
A description string
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
A device dict or None (None = unset).
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
See the `lxd-docs`_ for the details about the config and devices dicts.
See the `requests-docs` for the SSL stuff.
.. _lxd-docs: https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-10
.. _requests-docs: http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification # noqa
'''
ret = {
'name': name,
'description': description,
'config': config,
'devices': devices,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
profile = None
try:
profile = __salt__['lxd.profile_get'](
name, remote_addr, cert, key, verify_cert, _raw=True
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
pass
if description is None:
description = six.text_type()
if profile is None:
if __opts__['test']:
# Test is on, just return that we would create the profile
msg = 'Would create the profile "{0}"'.format(name)
ret['changes'] = {'created': msg}
return _unchanged(ret, msg)
# Create the profile
try:
__salt__['lxd.profile_create'](
name,
config,
devices,
description,
remote_addr,
cert,
key,
verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
msg = 'Profile "{0}" has been created'.format(name)
ret['changes'] = {'created': msg}
return _success(ret, msg)
config, devices = __salt__['lxd.normalize_input_values'](
config,
devices
)
#
# Description change
#
if six.text_type(profile.description) != six.text_type(description):
ret['changes']['description'] = (
'Description changed, from "{0}" to "{1}".'
).format(profile.description, description)
profile.description = description
changes = __salt__['lxd.sync_config_devices'](
profile, config, devices, __opts__['test']
)
ret['changes'].update(changes)
if not ret['changes']:
return _success(ret, 'No changes')
if __opts__['test']:
return _unchanged(
ret,
'Profile "{0}" would get changed.'.format(name)
)
try:
__salt__['lxd.pylxd_save_object'](profile)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
return _success(ret, '{0} changes'.format(len(ret['changes'].keys()))) | [
"def",
"present",
"(",
"name",
",",
"description",
"=",
"None",
",",
"config",
"=",
"None",
",",
"devices",
"=",
"None",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
... | Creates or updates LXD profiles
name :
The name of the profile to create/update
description :
A description string
config :
A config dict or None (None = unset).
Can also be a list:
[{'key': 'boot.autostart', 'value': 1},
{'key': 'security.privileged', 'value': '1'}]
devices :
A device dict or None (None = unset).
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
See the `lxd-docs`_ for the details about the config and devices dicts.
See the `requests-docs` for the SSL stuff.
.. _lxd-docs: https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-10
.. _requests-docs: http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification # noqa | [
"Creates",
"or",
"updates",
"LXD",
"profiles"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd_profile.py#L51-L192 | train |
saltstack/salt | salt/states/lxd_profile.py | absent | def absent(name, remote_addr=None, cert=None,
key=None, verify_cert=True):
'''
Ensure a LXD profile is not present, removing it if present.
name :
The name of the profile to remove.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
See the `requests-docs` for the SSL stuff.
.. _requests-docs: http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification # noqa
'''
ret = {
'name': name,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
if __opts__['test']:
try:
__salt__['lxd.profile_get'](
name, remote_addr, cert, key, verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
return _success(ret, 'Profile "{0}" not found.'.format(name))
ret['changes'] = {
'removed':
'Profile "{0}" would get deleted.'.format(name)
}
return _success(ret, ret['changes']['removed'])
try:
__salt__['lxd.profile_delete'](
name, remote_addr, cert, key, verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
return _success(ret, 'Profile "{0}" not found.'.format(name))
ret['changes'] = {
'removed':
'Profile "{0}" has been deleted.'.format(name)
}
return _success(ret, ret['changes']['removed']) | python | def absent(name, remote_addr=None, cert=None,
key=None, verify_cert=True):
'''
Ensure a LXD profile is not present, removing it if present.
name :
The name of the profile to remove.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
See the `requests-docs` for the SSL stuff.
.. _requests-docs: http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification # noqa
'''
ret = {
'name': name,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert,
'changes': {}
}
if __opts__['test']:
try:
__salt__['lxd.profile_get'](
name, remote_addr, cert, key, verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
return _success(ret, 'Profile "{0}" not found.'.format(name))
ret['changes'] = {
'removed':
'Profile "{0}" would get deleted.'.format(name)
}
return _success(ret, ret['changes']['removed'])
try:
__salt__['lxd.profile_delete'](
name, remote_addr, cert, key, verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
except SaltInvocationError as e:
# Profile not found
return _success(ret, 'Profile "{0}" not found.'.format(name))
ret['changes'] = {
'removed':
'Profile "{0}" has been deleted.'.format(name)
}
return _success(ret, ret['changes']['removed']) | [
"def",
"absent",
"(",
"name",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'remote_addr'",
":",
"remote_addr",
",",
"'cert... | Ensure a LXD profile is not present, removing it if present.
name :
The name of the profile to remove.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
PEM Formatted SSL Zertifikate.
Examples:
~/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
~/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
See the `requests-docs` for the SSL stuff.
.. _requests-docs: http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification # noqa | [
"Ensure",
"a",
"LXD",
"profile",
"is",
"not",
"present",
"removing",
"it",
"if",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd_profile.py#L195-L273 | train |
saltstack/salt | salt/modules/freebsdkmod.py | _get_persistent_modules | def _get_persistent_modules():
'''
Returns a list of modules in loader.conf that load on boot.
'''
mods = set()
with salt.utils.files.fopen(_LOADER_CONF, 'r') as loader_conf:
for line in loader_conf:
line = salt.utils.stringutils.to_unicode(line)
line = line.strip()
mod_name = _get_module_name(line)
if mod_name:
mods.add(mod_name)
return mods | python | def _get_persistent_modules():
'''
Returns a list of modules in loader.conf that load on boot.
'''
mods = set()
with salt.utils.files.fopen(_LOADER_CONF, 'r') as loader_conf:
for line in loader_conf:
line = salt.utils.stringutils.to_unicode(line)
line = line.strip()
mod_name = _get_module_name(line)
if mod_name:
mods.add(mod_name)
return mods | [
"def",
"_get_persistent_modules",
"(",
")",
":",
"mods",
"=",
"set",
"(",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"_LOADER_CONF",
",",
"'r'",
")",
"as",
"loader_conf",
":",
"for",
"line",
"in",
"loader_conf",
":",
"line",
"=... | Returns a list of modules in loader.conf that load on boot. | [
"Returns",
"a",
"list",
"of",
"modules",
"in",
"loader",
".",
"conf",
"that",
"load",
"on",
"boot",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdkmod.py#L68-L80 | train |
saltstack/salt | salt/modules/freebsdkmod.py | _set_persistent_module | def _set_persistent_module(mod):
'''
Add a module to loader.conf to make it persistent.
'''
if not mod or mod in mod_list(True) or mod not in \
available():
return set()
__salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod))
return set([mod]) | python | def _set_persistent_module(mod):
'''
Add a module to loader.conf to make it persistent.
'''
if not mod or mod in mod_list(True) or mod not in \
available():
return set()
__salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod))
return set([mod]) | [
"def",
"_set_persistent_module",
"(",
"mod",
")",
":",
"if",
"not",
"mod",
"or",
"mod",
"in",
"mod_list",
"(",
"True",
")",
"or",
"mod",
"not",
"in",
"available",
"(",
")",
":",
"return",
"set",
"(",
")",
"__salt__",
"[",
"'file.append'",
"]",
"(",
"... | Add a module to loader.conf to make it persistent. | [
"Add",
"a",
"module",
"to",
"loader",
".",
"conf",
"to",
"make",
"it",
"persistent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdkmod.py#L83-L91 | train |
saltstack/salt | salt/modules/freebsdkmod.py | _remove_persistent_module | def _remove_persistent_module(mod, comment):
'''
Remove module from loader.conf. If comment is true only comment line where
module is.
'''
if not mod or mod not in mod_list(True):
return set()
if comment:
__salt__['file.comment'](_LOADER_CONF, _MODULE_RE.format(mod))
else:
__salt__['file.sed'](_LOADER_CONF, _MODULE_RE.format(mod), '')
return set([mod]) | python | def _remove_persistent_module(mod, comment):
'''
Remove module from loader.conf. If comment is true only comment line where
module is.
'''
if not mod or mod not in mod_list(True):
return set()
if comment:
__salt__['file.comment'](_LOADER_CONF, _MODULE_RE.format(mod))
else:
__salt__['file.sed'](_LOADER_CONF, _MODULE_RE.format(mod), '')
return set([mod]) | [
"def",
"_remove_persistent_module",
"(",
"mod",
",",
"comment",
")",
":",
"if",
"not",
"mod",
"or",
"mod",
"not",
"in",
"mod_list",
"(",
"True",
")",
":",
"return",
"set",
"(",
")",
"if",
"comment",
":",
"__salt__",
"[",
"'file.comment'",
"]",
"(",
"_L... | Remove module from loader.conf. If comment is true only comment line where
module is. | [
"Remove",
"module",
"from",
"loader",
".",
"conf",
".",
"If",
"comment",
"is",
"true",
"only",
"comment",
"line",
"where",
"module",
"is",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdkmod.py#L94-L107 | train |
saltstack/salt | salt/modules/freebsdkmod.py | available | def available():
'''
Return a list of all available kernel modules
CLI Example:
.. code-block:: bash
salt '*' kmod.available
'''
ret = []
for path in __salt__['file.find']('/boot/kernel', name='*.ko$'):
bpath = os.path.basename(path)
comps = bpath.split('.')
if 'ko' in comps:
# This is a kernel module, return it without the .ko extension
ret.append('.'.join(comps[:comps.index('ko')]))
return ret | python | def available():
'''
Return a list of all available kernel modules
CLI Example:
.. code-block:: bash
salt '*' kmod.available
'''
ret = []
for path in __salt__['file.find']('/boot/kernel', name='*.ko$'):
bpath = os.path.basename(path)
comps = bpath.split('.')
if 'ko' in comps:
# This is a kernel module, return it without the .ko extension
ret.append('.'.join(comps[:comps.index('ko')]))
return ret | [
"def",
"available",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"path",
"in",
"__salt__",
"[",
"'file.find'",
"]",
"(",
"'/boot/kernel'",
",",
"name",
"=",
"'*.ko$'",
")",
":",
"bpath",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"co... | Return a list of all available kernel modules
CLI Example:
.. code-block:: bash
salt '*' kmod.available | [
"Return",
"a",
"list",
"of",
"all",
"available",
"kernel",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdkmod.py#L110-L127 | train |
saltstack/salt | salt/modules/freebsdkmod.py | lsmod | def lsmod():
'''
Return a dict containing information about currently loaded modules
CLI Example:
.. code-block:: bash
salt '*' kmod.lsmod
'''
ret = []
for line in __salt__['cmd.run']('kldstat').splitlines():
comps = line.split()
if not len(comps) > 2:
continue
if comps[0] == 'Id':
continue
if comps[4] == 'kernel':
continue
ret.append({
'module': comps[4][:-3],
'size': comps[3],
'depcount': comps[1]
})
return ret | python | def lsmod():
'''
Return a dict containing information about currently loaded modules
CLI Example:
.. code-block:: bash
salt '*' kmod.lsmod
'''
ret = []
for line in __salt__['cmd.run']('kldstat').splitlines():
comps = line.split()
if not len(comps) > 2:
continue
if comps[0] == 'Id':
continue
if comps[4] == 'kernel':
continue
ret.append({
'module': comps[4][:-3],
'size': comps[3],
'depcount': comps[1]
})
return ret | [
"def",
"lsmod",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"line",
"in",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'kldstat'",
")",
".",
"splitlines",
"(",
")",
":",
"comps",
"=",
"line",
".",
"split",
"(",
")",
"if",
"not",
"len",
"(",
"comps",
... | Return a dict containing information about currently loaded modules
CLI Example:
.. code-block:: bash
salt '*' kmod.lsmod | [
"Return",
"a",
"dict",
"containing",
"information",
"about",
"currently",
"loaded",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdkmod.py#L143-L167 | train |
saltstack/salt | salt/modules/freebsdkmod.py | mod_list | def mod_list(only_persist=False):
'''
Return a list of the loaded module names
CLI Example:
.. code-block:: bash
salt '*' kmod.mod_list
'''
mods = set()
if only_persist:
if not _get_persistent_modules():
return mods
for mod in _get_persistent_modules():
mods.add(mod)
else:
for mod in lsmod():
mods.add(mod['module'])
return sorted(list(mods)) | python | def mod_list(only_persist=False):
'''
Return a list of the loaded module names
CLI Example:
.. code-block:: bash
salt '*' kmod.mod_list
'''
mods = set()
if only_persist:
if not _get_persistent_modules():
return mods
for mod in _get_persistent_modules():
mods.add(mod)
else:
for mod in lsmod():
mods.add(mod['module'])
return sorted(list(mods)) | [
"def",
"mod_list",
"(",
"only_persist",
"=",
"False",
")",
":",
"mods",
"=",
"set",
"(",
")",
"if",
"only_persist",
":",
"if",
"not",
"_get_persistent_modules",
"(",
")",
":",
"return",
"mods",
"for",
"mod",
"in",
"_get_persistent_modules",
"(",
")",
":",
... | Return a list of the loaded module names
CLI Example:
.. code-block:: bash
salt '*' kmod.mod_list | [
"Return",
"a",
"list",
"of",
"the",
"loaded",
"module",
"names"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdkmod.py#L170-L189 | train |
saltstack/salt | salt/modules/freebsdkmod.py | load | def load(mod, persist=False):
'''
Load the specified kernel module
mod
Name of the module to add
persist
Write the module to sysrc kld_modules to make it load on system reboot
CLI Example:
.. code-block:: bash
salt '*' kmod.load bhyve
'''
pre_mods = lsmod()
response = __salt__['cmd.run_all']('kldload {0}'.format(mod),
python_shell=False)
if response['retcode'] == 0:
post_mods = lsmod()
mods = _new_mods(pre_mods, post_mods)
persist_mods = set()
if persist:
persist_mods = _set_persistent_module(mod)
return sorted(list(mods | persist_mods))
elif 'module already loaded or in kernel' in response['stderr']:
if persist and mod not in _get_persistent_modules():
persist_mods = _set_persistent_module(mod)
return sorted(list(persist_mods))
else:
# It's compiled into the kernel
return [None]
else:
return 'Module {0} not found'.format(mod) | python | def load(mod, persist=False):
'''
Load the specified kernel module
mod
Name of the module to add
persist
Write the module to sysrc kld_modules to make it load on system reboot
CLI Example:
.. code-block:: bash
salt '*' kmod.load bhyve
'''
pre_mods = lsmod()
response = __salt__['cmd.run_all']('kldload {0}'.format(mod),
python_shell=False)
if response['retcode'] == 0:
post_mods = lsmod()
mods = _new_mods(pre_mods, post_mods)
persist_mods = set()
if persist:
persist_mods = _set_persistent_module(mod)
return sorted(list(mods | persist_mods))
elif 'module already loaded or in kernel' in response['stderr']:
if persist and mod not in _get_persistent_modules():
persist_mods = _set_persistent_module(mod)
return sorted(list(persist_mods))
else:
# It's compiled into the kernel
return [None]
else:
return 'Module {0} not found'.format(mod) | [
"def",
"load",
"(",
"mod",
",",
"persist",
"=",
"False",
")",
":",
"pre_mods",
"=",
"lsmod",
"(",
")",
"response",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'kldload {0}'",
".",
"format",
"(",
"mod",
")",
",",
"python_shell",
"=",
"False",
")",... | Load the specified kernel module
mod
Name of the module to add
persist
Write the module to sysrc kld_modules to make it load on system reboot
CLI Example:
.. code-block:: bash
salt '*' kmod.load bhyve | [
"Load",
"the",
"specified",
"kernel",
"module"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdkmod.py#L192-L226 | train |
saltstack/salt | salt/modules/freebsdkmod.py | remove | def remove(mod, persist=False, comment=True):
'''
Remove the specified kernel module
mod
Name of module to remove
persist
Also remove module from /boot/loader.conf
comment
If persist is set don't remove line from /boot/loader.conf but only
comment it
CLI Example:
.. code-block:: bash
salt '*' kmod.remove vmm
'''
pre_mods = lsmod()
res = __salt__['cmd.run_all']('kldunload {0}'.format(mod),
python_shell=False)
if res['retcode'] == 0:
post_mods = lsmod()
mods = _rm_mods(pre_mods, post_mods)
persist_mods = set()
if persist:
persist_mods = _remove_persistent_module(mod, comment)
return sorted(list(mods | persist_mods))
else:
return 'Error removing module {0}: {1}'.format(mod, res['stderr']) | python | def remove(mod, persist=False, comment=True):
'''
Remove the specified kernel module
mod
Name of module to remove
persist
Also remove module from /boot/loader.conf
comment
If persist is set don't remove line from /boot/loader.conf but only
comment it
CLI Example:
.. code-block:: bash
salt '*' kmod.remove vmm
'''
pre_mods = lsmod()
res = __salt__['cmd.run_all']('kldunload {0}'.format(mod),
python_shell=False)
if res['retcode'] == 0:
post_mods = lsmod()
mods = _rm_mods(pre_mods, post_mods)
persist_mods = set()
if persist:
persist_mods = _remove_persistent_module(mod, comment)
return sorted(list(mods | persist_mods))
else:
return 'Error removing module {0}: {1}'.format(mod, res['stderr']) | [
"def",
"remove",
"(",
"mod",
",",
"persist",
"=",
"False",
",",
"comment",
"=",
"True",
")",
":",
"pre_mods",
"=",
"lsmod",
"(",
")",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'kldunload {0}'",
".",
"format",
"(",
"mod",
")",
",",
"pyt... | Remove the specified kernel module
mod
Name of module to remove
persist
Also remove module from /boot/loader.conf
comment
If persist is set don't remove line from /boot/loader.conf but only
comment it
CLI Example:
.. code-block:: bash
salt '*' kmod.remove vmm | [
"Remove",
"the",
"specified",
"kernel",
"module"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdkmod.py#L242-L273 | train |
saltstack/salt | salt/modules/serverdensity_device.py | get_sd_auth | def get_sd_auth(val, sd_auth_pillar_name='serverdensity'):
'''
Returns requested Server Density authentication value from pillar.
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.get_sd_auth <val>
'''
sd_pillar = __pillar__.get(sd_auth_pillar_name)
log.debug('Server Density Pillar: %s', sd_pillar)
if not sd_pillar:
log.error('Could not load %s pillar', sd_auth_pillar_name)
raise CommandExecutionError(
'{0} pillar is required for authentication'.format(sd_auth_pillar_name)
)
try:
return sd_pillar[val]
except KeyError:
log.error('Could not find value %s in pillar', val)
raise CommandExecutionError('{0} value was not found in pillar'.format(val)) | python | def get_sd_auth(val, sd_auth_pillar_name='serverdensity'):
'''
Returns requested Server Density authentication value from pillar.
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.get_sd_auth <val>
'''
sd_pillar = __pillar__.get(sd_auth_pillar_name)
log.debug('Server Density Pillar: %s', sd_pillar)
if not sd_pillar:
log.error('Could not load %s pillar', sd_auth_pillar_name)
raise CommandExecutionError(
'{0} pillar is required for authentication'.format(sd_auth_pillar_name)
)
try:
return sd_pillar[val]
except KeyError:
log.error('Could not find value %s in pillar', val)
raise CommandExecutionError('{0} value was not found in pillar'.format(val)) | [
"def",
"get_sd_auth",
"(",
"val",
",",
"sd_auth_pillar_name",
"=",
"'serverdensity'",
")",
":",
"sd_pillar",
"=",
"__pillar__",
".",
"get",
"(",
"sd_auth_pillar_name",
")",
"log",
".",
"debug",
"(",
"'Server Density Pillar: %s'",
",",
"sd_pillar",
")",
"if",
"no... | Returns requested Server Density authentication value from pillar.
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.get_sd_auth <val> | [
"Returns",
"requested",
"Server",
"Density",
"authentication",
"value",
"from",
"pillar",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/serverdensity_device.py#L43-L65 | train |
saltstack/salt | salt/modules/serverdensity_device.py | _clean_salt_variables | def _clean_salt_variables(params, variable_prefix="__"):
'''
Pops out variables from params which starts with `variable_prefix`.
'''
list(list(map(params.pop, [k for k in params if k.startswith(variable_prefix)])))
return params | python | def _clean_salt_variables(params, variable_prefix="__"):
'''
Pops out variables from params which starts with `variable_prefix`.
'''
list(list(map(params.pop, [k for k in params if k.startswith(variable_prefix)])))
return params | [
"def",
"_clean_salt_variables",
"(",
"params",
",",
"variable_prefix",
"=",
"\"__\"",
")",
":",
"list",
"(",
"list",
"(",
"map",
"(",
"params",
".",
"pop",
",",
"[",
"k",
"for",
"k",
"in",
"params",
"if",
"k",
".",
"startswith",
"(",
"variable_prefix",
... | Pops out variables from params which starts with `variable_prefix`. | [
"Pops",
"out",
"variables",
"from",
"params",
"which",
"starts",
"with",
"variable_prefix",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/serverdensity_device.py#L68-L73 | train |
saltstack/salt | salt/modules/serverdensity_device.py | create | def create(name, **params):
'''
Function to create device in Server Density. For more info, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.create lama
salt '*' serverdensity_device.create rich_lama group=lama_band installedRAM=32768
'''
log.debug('Server Density params: %s', params)
params = _clean_salt_variables(params)
params['name'] = name
api_response = requests.post(
'https://api.serverdensity.io/inventory/devices/',
params={'token': get_sd_auth('api_token')},
data=params
)
log.debug('Server Density API Response: %s', api_response)
log.debug('Server Density API Response content: %s', api_response.content)
if api_response.status_code == 200:
try:
return salt.utils.json.loads(api_response.content)
except ValueError:
log.error('Could not parse API Response content: %s', api_response.content)
raise CommandExecutionError(
'Failed to create, API Response: {0}'.format(api_response)
)
else:
return None | python | def create(name, **params):
'''
Function to create device in Server Density. For more info, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.create lama
salt '*' serverdensity_device.create rich_lama group=lama_band installedRAM=32768
'''
log.debug('Server Density params: %s', params)
params = _clean_salt_variables(params)
params['name'] = name
api_response = requests.post(
'https://api.serverdensity.io/inventory/devices/',
params={'token': get_sd_auth('api_token')},
data=params
)
log.debug('Server Density API Response: %s', api_response)
log.debug('Server Density API Response content: %s', api_response.content)
if api_response.status_code == 200:
try:
return salt.utils.json.loads(api_response.content)
except ValueError:
log.error('Could not parse API Response content: %s', api_response.content)
raise CommandExecutionError(
'Failed to create, API Response: {0}'.format(api_response)
)
else:
return None | [
"def",
"create",
"(",
"name",
",",
"*",
"*",
"params",
")",
":",
"log",
".",
"debug",
"(",
"'Server Density params: %s'",
",",
"params",
")",
"params",
"=",
"_clean_salt_variables",
"(",
"params",
")",
"params",
"[",
"'name'",
"]",
"=",
"name",
"api_respon... | Function to create device in Server Density. For more info, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.create lama
salt '*' serverdensity_device.create rich_lama group=lama_band installedRAM=32768 | [
"Function",
"to",
"create",
"device",
"in",
"Server",
"Density",
".",
"For",
"more",
"info",
"see",
"the",
"API",
"docs",
"__",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/serverdensity_device.py#L76-L110 | train |
saltstack/salt | salt/modules/serverdensity_device.py | delete | def delete(device_id):
'''
Delete a device from Server Density. For more information, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Deleting
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.delete 51f7eafcdba4bb235e000ae4
'''
api_response = requests.delete(
'https://api.serverdensity.io/inventory/devices/' + device_id,
params={'token': get_sd_auth('api_token')}
)
log.debug('Server Density API Response: %s', api_response)
log.debug('Server Density API Response content: %s', api_response.content)
if api_response.status_code == 200:
try:
return salt.utils.json.loads(api_response.content)
except ValueError:
log.error('Could not parse API Response content: %s', api_response.content)
raise CommandExecutionError(
'Failed to create, API Response: {0}'.format(api_response)
)
else:
return None | python | def delete(device_id):
'''
Delete a device from Server Density. For more information, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Deleting
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.delete 51f7eafcdba4bb235e000ae4
'''
api_response = requests.delete(
'https://api.serverdensity.io/inventory/devices/' + device_id,
params={'token': get_sd_auth('api_token')}
)
log.debug('Server Density API Response: %s', api_response)
log.debug('Server Density API Response content: %s', api_response.content)
if api_response.status_code == 200:
try:
return salt.utils.json.loads(api_response.content)
except ValueError:
log.error('Could not parse API Response content: %s', api_response.content)
raise CommandExecutionError(
'Failed to create, API Response: {0}'.format(api_response)
)
else:
return None | [
"def",
"delete",
"(",
"device_id",
")",
":",
"api_response",
"=",
"requests",
".",
"delete",
"(",
"'https://api.serverdensity.io/inventory/devices/'",
"+",
"device_id",
",",
"params",
"=",
"{",
"'token'",
":",
"get_sd_auth",
"(",
"'api_token'",
")",
"}",
")",
"l... | Delete a device from Server Density. For more information, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Deleting
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.delete 51f7eafcdba4bb235e000ae4 | [
"Delete",
"a",
"device",
"from",
"Server",
"Density",
".",
"For",
"more",
"information",
"see",
"the",
"API",
"docs",
"__",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/serverdensity_device.py#L113-L141 | train |
saltstack/salt | salt/modules/serverdensity_device.py | ls | def ls(**params):
'''
List devices in Server Density
Results will be filtered by any params passed to this function. For more
information, see the API docs on listing_ and searching_.
.. _listing: https://apidocs.serverdensity.com/Inventory/Devices/Listing
.. _searching: https://apidocs.serverdensity.com/Inventory/Devices/Searching
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.ls
salt '*' serverdensity_device.ls name=lama
salt '*' serverdensity_device.ls name=lama group=lama_band installedRAM=32768
'''
params = _clean_salt_variables(params)
endpoint = 'devices'
# Change endpoint if there are params to filter by:
if params:
endpoint = 'resources'
# Convert all ints to strings:
for key, val in six.iteritems(params):
params[key] = six.text_type(val)
api_response = requests.get(
'https://api.serverdensity.io/inventory/{0}'.format(endpoint),
params={'token': get_sd_auth('api_token'), 'filter': salt.utils.json.dumps(params)}
)
log.debug('Server Density API Response: %s', api_response)
log.debug('Server Density API Response content: %s', api_response.content)
if api_response.status_code == 200:
try:
return salt.utils.json.loads(api_response.content)
except ValueError:
log.error(
'Could not parse Server Density API Response content: %s',
api_response.content
)
raise CommandExecutionError(
'Failed to create, Server Density API Response: {0}'
.format(api_response)
)
else:
return None | python | def ls(**params):
'''
List devices in Server Density
Results will be filtered by any params passed to this function. For more
information, see the API docs on listing_ and searching_.
.. _listing: https://apidocs.serverdensity.com/Inventory/Devices/Listing
.. _searching: https://apidocs.serverdensity.com/Inventory/Devices/Searching
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.ls
salt '*' serverdensity_device.ls name=lama
salt '*' serverdensity_device.ls name=lama group=lama_band installedRAM=32768
'''
params = _clean_salt_variables(params)
endpoint = 'devices'
# Change endpoint if there are params to filter by:
if params:
endpoint = 'resources'
# Convert all ints to strings:
for key, val in six.iteritems(params):
params[key] = six.text_type(val)
api_response = requests.get(
'https://api.serverdensity.io/inventory/{0}'.format(endpoint),
params={'token': get_sd_auth('api_token'), 'filter': salt.utils.json.dumps(params)}
)
log.debug('Server Density API Response: %s', api_response)
log.debug('Server Density API Response content: %s', api_response.content)
if api_response.status_code == 200:
try:
return salt.utils.json.loads(api_response.content)
except ValueError:
log.error(
'Could not parse Server Density API Response content: %s',
api_response.content
)
raise CommandExecutionError(
'Failed to create, Server Density API Response: {0}'
.format(api_response)
)
else:
return None | [
"def",
"ls",
"(",
"*",
"*",
"params",
")",
":",
"params",
"=",
"_clean_salt_variables",
"(",
"params",
")",
"endpoint",
"=",
"'devices'",
"# Change endpoint if there are params to filter by:",
"if",
"params",
":",
"endpoint",
"=",
"'resources'",
"# Convert all ints to... | List devices in Server Density
Results will be filtered by any params passed to this function. For more
information, see the API docs on listing_ and searching_.
.. _listing: https://apidocs.serverdensity.com/Inventory/Devices/Listing
.. _searching: https://apidocs.serverdensity.com/Inventory/Devices/Searching
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.ls
salt '*' serverdensity_device.ls name=lama
salt '*' serverdensity_device.ls name=lama group=lama_band installedRAM=32768 | [
"List",
"devices",
"in",
"Server",
"Density"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/serverdensity_device.py#L144-L193 | train |
saltstack/salt | salt/modules/serverdensity_device.py | update | def update(device_id, **params):
'''
Updates device information in Server Density. For more information see the
`API docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Updating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.update 51f7eafcdba4bb235e000ae4 name=lama group=lama_band
salt '*' serverdensity_device.update 51f7eafcdba4bb235e000ae4 name=better_lama group=rock_lamas swapSpace=512
'''
params = _clean_salt_variables(params)
api_response = requests.put(
'https://api.serverdensity.io/inventory/devices/' + device_id,
params={'token': get_sd_auth('api_token')},
data=params
)
log.debug('Server Density API Response: %s', api_response)
log.debug('Server Density API Response content: %s', api_response.content)
if api_response.status_code == 200:
try:
return salt.utils.json.loads(api_response.content)
except ValueError:
log.error(
'Could not parse Server Density API Response content: %s',
api_response.content
)
raise CommandExecutionError(
'Failed to create, API Response: {0}'.format(api_response)
)
else:
return None | python | def update(device_id, **params):
'''
Updates device information in Server Density. For more information see the
`API docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Updating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.update 51f7eafcdba4bb235e000ae4 name=lama group=lama_band
salt '*' serverdensity_device.update 51f7eafcdba4bb235e000ae4 name=better_lama group=rock_lamas swapSpace=512
'''
params = _clean_salt_variables(params)
api_response = requests.put(
'https://api.serverdensity.io/inventory/devices/' + device_id,
params={'token': get_sd_auth('api_token')},
data=params
)
log.debug('Server Density API Response: %s', api_response)
log.debug('Server Density API Response content: %s', api_response.content)
if api_response.status_code == 200:
try:
return salt.utils.json.loads(api_response.content)
except ValueError:
log.error(
'Could not parse Server Density API Response content: %s',
api_response.content
)
raise CommandExecutionError(
'Failed to create, API Response: {0}'.format(api_response)
)
else:
return None | [
"def",
"update",
"(",
"device_id",
",",
"*",
"*",
"params",
")",
":",
"params",
"=",
"_clean_salt_variables",
"(",
"params",
")",
"api_response",
"=",
"requests",
".",
"put",
"(",
"'https://api.serverdensity.io/inventory/devices/'",
"+",
"device_id",
",",
"params"... | Updates device information in Server Density. For more information see the
`API docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Updating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.update 51f7eafcdba4bb235e000ae4 name=lama group=lama_band
salt '*' serverdensity_device.update 51f7eafcdba4bb235e000ae4 name=better_lama group=rock_lamas swapSpace=512 | [
"Updates",
"device",
"information",
"in",
"Server",
"Density",
".",
"For",
"more",
"information",
"see",
"the",
"API",
"docs",
"__",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/serverdensity_device.py#L196-L231 | train |
saltstack/salt | salt/modules/serverdensity_device.py | install_agent | def install_agent(agent_key, agent_version=1):
'''
Function downloads Server Density installation agent, and installs sd-agent
with agent_key. Optionally the agent_version would select the series to
use (defaults on the v1 one).
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498
salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498 2
'''
work_dir = os.path.join(__opts__['cachedir'], 'tmp')
if not os.path.isdir(work_dir):
os.mkdir(work_dir)
install_file = tempfile.NamedTemporaryFile(dir=work_dir,
suffix='.sh',
delete=False)
install_filename = install_file.name
install_file.close()
account_field = 'account_url'
url = 'https://www.serverdensity.com/downloads/agent-install.sh'
if agent_version == 2:
account_field = 'account_name'
url = 'https://archive.serverdensity.com/agent-install.sh'
account = get_sd_auth(account_field)
__salt__['cmd.run'](
cmd='curl -L {0} -o {1}'.format(url, install_filename),
cwd=work_dir
)
__salt__['cmd.run'](cmd='chmod +x {0}'.format(install_filename), cwd=work_dir)
return __salt__['cmd.run'](
cmd='{filename} -a {account} -k {agent_key}'.format(
filename=install_filename, account=account, agent_key=agent_key),
cwd=work_dir
) | python | def install_agent(agent_key, agent_version=1):
'''
Function downloads Server Density installation agent, and installs sd-agent
with agent_key. Optionally the agent_version would select the series to
use (defaults on the v1 one).
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498
salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498 2
'''
work_dir = os.path.join(__opts__['cachedir'], 'tmp')
if not os.path.isdir(work_dir):
os.mkdir(work_dir)
install_file = tempfile.NamedTemporaryFile(dir=work_dir,
suffix='.sh',
delete=False)
install_filename = install_file.name
install_file.close()
account_field = 'account_url'
url = 'https://www.serverdensity.com/downloads/agent-install.sh'
if agent_version == 2:
account_field = 'account_name'
url = 'https://archive.serverdensity.com/agent-install.sh'
account = get_sd_auth(account_field)
__salt__['cmd.run'](
cmd='curl -L {0} -o {1}'.format(url, install_filename),
cwd=work_dir
)
__salt__['cmd.run'](cmd='chmod +x {0}'.format(install_filename), cwd=work_dir)
return __salt__['cmd.run'](
cmd='{filename} -a {account} -k {agent_key}'.format(
filename=install_filename, account=account, agent_key=agent_key),
cwd=work_dir
) | [
"def",
"install_agent",
"(",
"agent_key",
",",
"agent_version",
"=",
"1",
")",
":",
"work_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'tmp'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"work_... | Function downloads Server Density installation agent, and installs sd-agent
with agent_key. Optionally the agent_version would select the series to
use (defaults on the v1 one).
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498
salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498 2 | [
"Function",
"downloads",
"Server",
"Density",
"installation",
"agent",
"and",
"installs",
"sd",
"-",
"agent",
"with",
"agent_key",
".",
"Optionally",
"the",
"agent_version",
"would",
"select",
"the",
"series",
"to",
"use",
"(",
"defaults",
"on",
"the",
"v1",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/serverdensity_device.py#L234-L274 | train |
saltstack/salt | salt/cache/etcd_cache.py | _init_client | def _init_client():
'''Setup client and init datastore.
'''
global client, path_prefix
if client is not None:
return
etcd_kwargs = {
'host': __opts__.get('etcd.host', '127.0.0.1'),
'port': __opts__.get('etcd.port', 2379),
'protocol': __opts__.get('etcd.protocol', 'http'),
'allow_reconnect': __opts__.get('etcd.allow_reconnect', True),
'allow_redirect': __opts__.get('etcd.allow_redirect', False),
'srv_domain': __opts__.get('etcd.srv_domain', None),
'read_timeout': __opts__.get('etcd.read_timeout', 60),
'username': __opts__.get('etcd.username', None),
'password': __opts__.get('etcd.password', None),
'cert': __opts__.get('etcd.cert', None),
'ca_cert': __opts__.get('etcd.ca_cert', None),
}
path_prefix = __opts__.get('etcd.path_prefix', _DEFAULT_PATH_PREFIX)
if path_prefix != "":
path_prefix = '/{0}'.format(path_prefix.strip('/'))
log.info("etcd: Setting up client with params: %r", etcd_kwargs)
client = etcd.Client(**etcd_kwargs)
try:
client.read(path_prefix)
except etcd.EtcdKeyNotFound:
log.info("etcd: Creating dir %r", path_prefix)
client.write(path_prefix, None, dir=True) | python | def _init_client():
'''Setup client and init datastore.
'''
global client, path_prefix
if client is not None:
return
etcd_kwargs = {
'host': __opts__.get('etcd.host', '127.0.0.1'),
'port': __opts__.get('etcd.port', 2379),
'protocol': __opts__.get('etcd.protocol', 'http'),
'allow_reconnect': __opts__.get('etcd.allow_reconnect', True),
'allow_redirect': __opts__.get('etcd.allow_redirect', False),
'srv_domain': __opts__.get('etcd.srv_domain', None),
'read_timeout': __opts__.get('etcd.read_timeout', 60),
'username': __opts__.get('etcd.username', None),
'password': __opts__.get('etcd.password', None),
'cert': __opts__.get('etcd.cert', None),
'ca_cert': __opts__.get('etcd.ca_cert', None),
}
path_prefix = __opts__.get('etcd.path_prefix', _DEFAULT_PATH_PREFIX)
if path_prefix != "":
path_prefix = '/{0}'.format(path_prefix.strip('/'))
log.info("etcd: Setting up client with params: %r", etcd_kwargs)
client = etcd.Client(**etcd_kwargs)
try:
client.read(path_prefix)
except etcd.EtcdKeyNotFound:
log.info("etcd: Creating dir %r", path_prefix)
client.write(path_prefix, None, dir=True) | [
"def",
"_init_client",
"(",
")",
":",
"global",
"client",
",",
"path_prefix",
"if",
"client",
"is",
"not",
"None",
":",
"return",
"etcd_kwargs",
"=",
"{",
"'host'",
":",
"__opts__",
".",
"get",
"(",
"'etcd.host'",
",",
"'127.0.0.1'",
")",
",",
"'port'",
... | Setup client and init datastore. | [
"Setup",
"client",
"and",
"init",
"datastore",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/etcd_cache.py#L90-L119 | train |
saltstack/salt | salt/cache/etcd_cache.py | store | def store(bank, key, data):
'''
Store a key value.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
value = __context__['serial'].dumps(data)
client.write(etcd_key, base64.b64encode(value))
except Exception as exc:
raise SaltCacheError(
'There was an error writing the key, {0}: {1}'.format(etcd_key, exc)
) | python | def store(bank, key, data):
'''
Store a key value.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
value = __context__['serial'].dumps(data)
client.write(etcd_key, base64.b64encode(value))
except Exception as exc:
raise SaltCacheError(
'There was an error writing the key, {0}: {1}'.format(etcd_key, exc)
) | [
"def",
"store",
"(",
"bank",
",",
"key",
",",
"data",
")",
":",
"_init_client",
"(",
")",
"etcd_key",
"=",
"'{0}/{1}/{2}'",
".",
"format",
"(",
"path_prefix",
",",
"bank",
",",
"key",
")",
"try",
":",
"value",
"=",
"__context__",
"[",
"'serial'",
"]",
... | Store a key value. | [
"Store",
"a",
"key",
"value",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/etcd_cache.py#L122-L134 | train |
saltstack/salt | salt/cache/etcd_cache.py | fetch | def fetch(bank, key):
'''
Fetch a key value.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
value = client.read(etcd_key).value
return __context__['serial'].loads(base64.b64decode(value))
except etcd.EtcdKeyNotFound:
return {}
except Exception as exc:
raise SaltCacheError(
'There was an error reading the key, {0}: {1}'.format(
etcd_key, exc
)
) | python | def fetch(bank, key):
'''
Fetch a key value.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
value = client.read(etcd_key).value
return __context__['serial'].loads(base64.b64decode(value))
except etcd.EtcdKeyNotFound:
return {}
except Exception as exc:
raise SaltCacheError(
'There was an error reading the key, {0}: {1}'.format(
etcd_key, exc
)
) | [
"def",
"fetch",
"(",
"bank",
",",
"key",
")",
":",
"_init_client",
"(",
")",
"etcd_key",
"=",
"'{0}/{1}/{2}'",
".",
"format",
"(",
"path_prefix",
",",
"bank",
",",
"key",
")",
"try",
":",
"value",
"=",
"client",
".",
"read",
"(",
"etcd_key",
")",
"."... | Fetch a key value. | [
"Fetch",
"a",
"key",
"value",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/etcd_cache.py#L137-L153 | train |
saltstack/salt | salt/cache/etcd_cache.py | flush | def flush(bank, key=None):
'''
Remove the key from the cache bank with all the key content.
'''
_init_client()
if key is None:
etcd_key = '{0}/{1}'.format(path_prefix, bank)
else:
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
client.read(etcd_key)
except etcd.EtcdKeyNotFound:
return # nothing to flush
try:
client.delete(etcd_key, recursive=True)
except Exception as exc:
raise SaltCacheError(
'There was an error removing the key, {0}: {1}'.format(
etcd_key, exc
)
) | python | def flush(bank, key=None):
'''
Remove the key from the cache bank with all the key content.
'''
_init_client()
if key is None:
etcd_key = '{0}/{1}'.format(path_prefix, bank)
else:
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
client.read(etcd_key)
except etcd.EtcdKeyNotFound:
return # nothing to flush
try:
client.delete(etcd_key, recursive=True)
except Exception as exc:
raise SaltCacheError(
'There was an error removing the key, {0}: {1}'.format(
etcd_key, exc
)
) | [
"def",
"flush",
"(",
"bank",
",",
"key",
"=",
"None",
")",
":",
"_init_client",
"(",
")",
"if",
"key",
"is",
"None",
":",
"etcd_key",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"path_prefix",
",",
"bank",
")",
"else",
":",
"etcd_key",
"=",
"'{0}/{1}/{2}'",
... | Remove the key from the cache bank with all the key content. | [
"Remove",
"the",
"key",
"from",
"the",
"cache",
"bank",
"with",
"all",
"the",
"key",
"content",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/etcd_cache.py#L156-L176 | train |
saltstack/salt | salt/cache/etcd_cache.py | _walk | def _walk(r):
'''
Recursively walk dirs. Return flattened list of keys.
r: etcd.EtcdResult
'''
if not r.dir:
return [r.key.split('/', 3)[3]]
keys = []
for c in client.read(r.key).children:
keys.extend(_walk(c))
return keys | python | def _walk(r):
'''
Recursively walk dirs. Return flattened list of keys.
r: etcd.EtcdResult
'''
if not r.dir:
return [r.key.split('/', 3)[3]]
keys = []
for c in client.read(r.key).children:
keys.extend(_walk(c))
return keys | [
"def",
"_walk",
"(",
"r",
")",
":",
"if",
"not",
"r",
".",
"dir",
":",
"return",
"[",
"r",
".",
"key",
".",
"split",
"(",
"'/'",
",",
"3",
")",
"[",
"3",
"]",
"]",
"keys",
"=",
"[",
"]",
"for",
"c",
"in",
"client",
".",
"read",
"(",
"r",
... | Recursively walk dirs. Return flattened list of keys.
r: etcd.EtcdResult | [
"Recursively",
"walk",
"dirs",
".",
"Return",
"flattened",
"list",
"of",
"keys",
".",
"r",
":",
"etcd",
".",
"EtcdResult"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/etcd_cache.py#L179-L190 | train |
saltstack/salt | salt/cache/etcd_cache.py | ls | def ls(bank):
'''
Return an iterable object containing all entries stored in the specified
bank.
'''
_init_client()
path = '{0}/{1}'.format(path_prefix, bank)
try:
return _walk(client.read(path))
except Exception as exc:
raise SaltCacheError(
'There was an error getting the key "{0}": {1}'.format(
bank, exc
)
) | python | def ls(bank):
'''
Return an iterable object containing all entries stored in the specified
bank.
'''
_init_client()
path = '{0}/{1}'.format(path_prefix, bank)
try:
return _walk(client.read(path))
except Exception as exc:
raise SaltCacheError(
'There was an error getting the key "{0}": {1}'.format(
bank, exc
)
) | [
"def",
"ls",
"(",
"bank",
")",
":",
"_init_client",
"(",
")",
"path",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"path_prefix",
",",
"bank",
")",
"try",
":",
"return",
"_walk",
"(",
"client",
".",
"read",
"(",
"path",
")",
")",
"except",
"Exception",
"as"... | Return an iterable object containing all entries stored in the specified
bank. | [
"Return",
"an",
"iterable",
"object",
"containing",
"all",
"entries",
"stored",
"in",
"the",
"specified",
"bank",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/etcd_cache.py#L193-L207 | train |
saltstack/salt | salt/cache/etcd_cache.py | contains | def contains(bank, key):
'''
Checks if the specified bank contains the specified key.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
r = client.read(etcd_key)
# return True for keys, not dirs
return r.dir is False
except etcd.EtcdKeyNotFound:
return False
except Exception as exc:
raise SaltCacheError(
'There was an error getting the key, {0}: {1}'.format(
etcd_key, exc
)
) | python | def contains(bank, key):
'''
Checks if the specified bank contains the specified key.
'''
_init_client()
etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key)
try:
r = client.read(etcd_key)
# return True for keys, not dirs
return r.dir is False
except etcd.EtcdKeyNotFound:
return False
except Exception as exc:
raise SaltCacheError(
'There was an error getting the key, {0}: {1}'.format(
etcd_key, exc
)
) | [
"def",
"contains",
"(",
"bank",
",",
"key",
")",
":",
"_init_client",
"(",
")",
"etcd_key",
"=",
"'{0}/{1}/{2}'",
".",
"format",
"(",
"path_prefix",
",",
"bank",
",",
"key",
")",
"try",
":",
"r",
"=",
"client",
".",
"read",
"(",
"etcd_key",
")",
"# r... | Checks if the specified bank contains the specified key. | [
"Checks",
"if",
"the",
"specified",
"bank",
"contains",
"the",
"specified",
"key",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/etcd_cache.py#L210-L227 | train |
saltstack/salt | salt/modules/udev.py | _parse_udevadm_info | def _parse_udevadm_info(udev_info):
'''
Parse the info returned by udevadm command.
'''
devices = []
dev = {}
for line in (line.strip() for line in udev_info.splitlines()):
if line:
line = line.split(':', 1)
if len(line) != 2:
continue
query, data = line
if query == 'E':
if query not in dev:
dev[query] = {}
key, val = data.strip().split('=', 1)
try:
val = int(val)
except ValueError:
try:
val = float(val)
except ValueError:
pass # Quiet, this is not a number.
dev[query][key] = val
else:
if query not in dev:
dev[query] = []
dev[query].append(data.strip())
else:
if dev:
devices.append(_normalize_info(dev))
dev = {}
if dev:
_normalize_info(dev)
devices.append(_normalize_info(dev))
return devices | python | def _parse_udevadm_info(udev_info):
'''
Parse the info returned by udevadm command.
'''
devices = []
dev = {}
for line in (line.strip() for line in udev_info.splitlines()):
if line:
line = line.split(':', 1)
if len(line) != 2:
continue
query, data = line
if query == 'E':
if query not in dev:
dev[query] = {}
key, val = data.strip().split('=', 1)
try:
val = int(val)
except ValueError:
try:
val = float(val)
except ValueError:
pass # Quiet, this is not a number.
dev[query][key] = val
else:
if query not in dev:
dev[query] = []
dev[query].append(data.strip())
else:
if dev:
devices.append(_normalize_info(dev))
dev = {}
if dev:
_normalize_info(dev)
devices.append(_normalize_info(dev))
return devices | [
"def",
"_parse_udevadm_info",
"(",
"udev_info",
")",
":",
"devices",
"=",
"[",
"]",
"dev",
"=",
"{",
"}",
"for",
"line",
"in",
"(",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"udev_info",
".",
"splitlines",
"(",
")",
")",
":",
"if",
"line... | Parse the info returned by udevadm command. | [
"Parse",
"the",
"info",
"returned",
"by",
"udevadm",
"command",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/udev.py#L31-L70 | train |
saltstack/salt | salt/modules/udev.py | _normalize_info | def _normalize_info(dev):
'''
Replace list with only one element to the value of the element.
:param dev:
:return:
'''
for sect, val in dev.items():
if len(val) == 1:
dev[sect] = val[0]
return dev | python | def _normalize_info(dev):
'''
Replace list with only one element to the value of the element.
:param dev:
:return:
'''
for sect, val in dev.items():
if len(val) == 1:
dev[sect] = val[0]
return dev | [
"def",
"_normalize_info",
"(",
"dev",
")",
":",
"for",
"sect",
",",
"val",
"in",
"dev",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"val",
")",
"==",
"1",
":",
"dev",
"[",
"sect",
"]",
"=",
"val",
"[",
"0",
"]",
"return",
"dev"
] | Replace list with only one element to the value of the element.
:param dev:
:return: | [
"Replace",
"list",
"with",
"only",
"one",
"element",
"to",
"the",
"value",
"of",
"the",
"element",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/udev.py#L73-L84 | train |
saltstack/salt | salt/modules/udev.py | info | def info(dev):
'''
Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
salt '*' udev.info /sys/class/net/eth0
'''
if 'sys' in dev:
qtype = 'path'
else:
qtype = 'name'
cmd = 'udevadm info --export --query=all --{0}={1}'.format(qtype, dev)
udev_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if udev_result['retcode'] != 0:
raise CommandExecutionError(udev_result['stderr'])
return _parse_udevadm_info(udev_result['stdout'])[0] | python | def info(dev):
'''
Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
salt '*' udev.info /sys/class/net/eth0
'''
if 'sys' in dev:
qtype = 'path'
else:
qtype = 'name'
cmd = 'udevadm info --export --query=all --{0}={1}'.format(qtype, dev)
udev_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if udev_result['retcode'] != 0:
raise CommandExecutionError(udev_result['stderr'])
return _parse_udevadm_info(udev_result['stdout'])[0] | [
"def",
"info",
"(",
"dev",
")",
":",
"if",
"'sys'",
"in",
"dev",
":",
"qtype",
"=",
"'path'",
"else",
":",
"qtype",
"=",
"'name'",
"cmd",
"=",
"'udevadm info --export --query=all --{0}={1}'",
".",
"format",
"(",
"qtype",
",",
"dev",
")",
"udev_result",
"="... | Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
salt '*' udev.info /sys/class/net/eth0 | [
"Extract",
"all",
"info",
"delivered",
"by",
"udevadm"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/udev.py#L87-L109 | train |
saltstack/salt | salt/modules/udev.py | exportdb | def exportdb():
'''
Return all the udev database
CLI Example:
.. code-block:: bash
salt '*' udev.exportdb
'''
cmd = 'udevadm info --export-db'
udev_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if udev_result['retcode']:
raise CommandExecutionError(udev_result['stderr'])
return _parse_udevadm_info(udev_result['stdout']) | python | def exportdb():
'''
Return all the udev database
CLI Example:
.. code-block:: bash
salt '*' udev.exportdb
'''
cmd = 'udevadm info --export-db'
udev_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if udev_result['retcode']:
raise CommandExecutionError(udev_result['stderr'])
return _parse_udevadm_info(udev_result['stdout']) | [
"def",
"exportdb",
"(",
")",
":",
"cmd",
"=",
"'udevadm info --export-db'",
"udev_result",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"output_loglevel",
"=",
"'quiet'",
")",
"if",
"udev_result",
"[",
"'retcode'",
"]",
":",
"raise",
"CommandEx... | Return all the udev database
CLI Example:
.. code-block:: bash
salt '*' udev.exportdb | [
"Return",
"all",
"the",
"udev",
"database"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/udev.py#L168-L185 | train |
saltstack/salt | salt/modules/mac_timezone.py | _get_date_time_format | def _get_date_time_format(dt_string):
'''
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
:raises: SaltInvocationError on Invalid Date/Time string
'''
valid_formats = [
'%H:%M',
'%H:%M:%S',
'%m:%d:%y',
'%m:%d:%Y',
'%m/%d/%y',
'%m/%d/%Y'
]
for dt_format in valid_formats:
try:
datetime.strptime(dt_string, dt_format)
return dt_format
except ValueError:
continue
msg = 'Invalid Date/Time Format: {0}'.format(dt_string)
raise SaltInvocationError(msg) | python | def _get_date_time_format(dt_string):
'''
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
:raises: SaltInvocationError on Invalid Date/Time string
'''
valid_formats = [
'%H:%M',
'%H:%M:%S',
'%m:%d:%y',
'%m:%d:%Y',
'%m/%d/%y',
'%m/%d/%Y'
]
for dt_format in valid_formats:
try:
datetime.strptime(dt_string, dt_format)
return dt_format
except ValueError:
continue
msg = 'Invalid Date/Time Format: {0}'.format(dt_string)
raise SaltInvocationError(msg) | [
"def",
"_get_date_time_format",
"(",
"dt_string",
")",
":",
"valid_formats",
"=",
"[",
"'%H:%M'",
",",
"'%H:%M:%S'",
",",
"'%m:%d:%y'",
",",
"'%m:%d:%Y'",
",",
"'%m/%d/%y'",
",",
"'%m/%d/%Y'",
"]",
"for",
"dt_format",
"in",
"valid_formats",
":",
"try",
":",
"d... | Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
:raises: SaltInvocationError on Invalid Date/Time string | [
"Function",
"that",
"detects",
"the",
"date",
"/",
"time",
"format",
"for",
"the",
"string",
"passed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L31-L58 | train |
saltstack/salt | salt/modules/mac_timezone.py | get_date | def get_date():
'''
Displays the current date
:return: the system date
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_date
'''
ret = salt.utils.mac_utils.execute_return_result('systemsetup -getdate')
return salt.utils.mac_utils.parse_return(ret) | python | def get_date():
'''
Displays the current date
:return: the system date
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_date
'''
ret = salt.utils.mac_utils.execute_return_result('systemsetup -getdate')
return salt.utils.mac_utils.parse_return(ret) | [
"def",
"get_date",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getdate'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | Displays the current date
:return: the system date
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_date | [
"Displays",
"the",
"current",
"date"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L61-L75 | train |
saltstack/salt | salt/modules/mac_timezone.py | set_date | def set_date(date):
'''
Set the current month, day, and year
:param str date: The date to set. Valid date formats are:
- %m:%d:%y
- %m:%d:%Y
- %m/%d/%y
- %m/%d/%Y
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Date format
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_date 1/13/2016
'''
date_format = _get_date_time_format(date)
dt_obj = datetime.strptime(date, date_format)
cmd = 'systemsetup -setdate {0}'.format(dt_obj.strftime('%m:%d:%Y'))
return salt.utils.mac_utils.execute_return_success(cmd) | python | def set_date(date):
'''
Set the current month, day, and year
:param str date: The date to set. Valid date formats are:
- %m:%d:%y
- %m:%d:%Y
- %m/%d/%y
- %m/%d/%Y
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Date format
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_date 1/13/2016
'''
date_format = _get_date_time_format(date)
dt_obj = datetime.strptime(date, date_format)
cmd = 'systemsetup -setdate {0}'.format(dt_obj.strftime('%m:%d:%Y'))
return salt.utils.mac_utils.execute_return_success(cmd) | [
"def",
"set_date",
"(",
"date",
")",
":",
"date_format",
"=",
"_get_date_time_format",
"(",
"date",
")",
"dt_obj",
"=",
"datetime",
".",
"strptime",
"(",
"date",
",",
"date_format",
")",
"cmd",
"=",
"'systemsetup -setdate {0}'",
".",
"format",
"(",
"dt_obj",
... | Set the current month, day, and year
:param str date: The date to set. Valid date formats are:
- %m:%d:%y
- %m:%d:%Y
- %m/%d/%y
- %m/%d/%Y
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Date format
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_date 1/13/2016 | [
"Set",
"the",
"current",
"month",
"day",
"and",
"year"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L78-L105 | train |
saltstack/salt | salt/modules/mac_timezone.py | get_time | def get_time():
'''
Get the current system time.
:return: The current time in 24 hour format
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time
'''
ret = salt.utils.mac_utils.execute_return_result('systemsetup -gettime')
return salt.utils.mac_utils.parse_return(ret) | python | def get_time():
'''
Get the current system time.
:return: The current time in 24 hour format
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time
'''
ret = salt.utils.mac_utils.execute_return_result('systemsetup -gettime')
return salt.utils.mac_utils.parse_return(ret) | [
"def",
"get_time",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -gettime'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | Get the current system time.
:return: The current time in 24 hour format
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time | [
"Get",
"the",
"current",
"system",
"time",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L108-L122 | train |
saltstack/salt | salt/modules/mac_timezone.py | set_time | def set_time(time):
'''
Sets the current time. Must be in 24 hour format.
:param str time: The time to set in 24 hour format. The value must be
double quoted. ie: '"17:46"'
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Time format
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_time '"17:34"'
'''
# time must be double quoted '"17:46"'
time_format = _get_date_time_format(time)
dt_obj = datetime.strptime(time, time_format)
cmd = 'systemsetup -settime {0}'.format(dt_obj.strftime('%H:%M:%S'))
return salt.utils.mac_utils.execute_return_success(cmd) | python | def set_time(time):
'''
Sets the current time. Must be in 24 hour format.
:param str time: The time to set in 24 hour format. The value must be
double quoted. ie: '"17:46"'
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Time format
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_time '"17:34"'
'''
# time must be double quoted '"17:46"'
time_format = _get_date_time_format(time)
dt_obj = datetime.strptime(time, time_format)
cmd = 'systemsetup -settime {0}'.format(dt_obj.strftime('%H:%M:%S'))
return salt.utils.mac_utils.execute_return_success(cmd) | [
"def",
"set_time",
"(",
"time",
")",
":",
"# time must be double quoted '\"17:46\"'",
"time_format",
"=",
"_get_date_time_format",
"(",
"time",
")",
"dt_obj",
"=",
"datetime",
".",
"strptime",
"(",
"time",
",",
"time_format",
")",
"cmd",
"=",
"'systemsetup -settime ... | Sets the current time. Must be in 24 hour format.
:param str time: The time to set in 24 hour format. The value must be
double quoted. ie: '"17:46"'
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Time format
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_time '"17:34"' | [
"Sets",
"the",
"current",
"time",
".",
"Must",
"be",
"in",
"24",
"hour",
"format",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L125-L149 | train |
saltstack/salt | salt/modules/mac_timezone.py | get_zone | def get_zone():
'''
Displays the current time zone
:return: The current time zone
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone
'''
ret = salt.utils.mac_utils.execute_return_result('systemsetup -gettimezone')
return salt.utils.mac_utils.parse_return(ret) | python | def get_zone():
'''
Displays the current time zone
:return: The current time zone
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone
'''
ret = salt.utils.mac_utils.execute_return_result('systemsetup -gettimezone')
return salt.utils.mac_utils.parse_return(ret) | [
"def",
"get_zone",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -gettimezone'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | Displays the current time zone
:return: The current time zone
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone | [
"Displays",
"the",
"current",
"time",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L152-L166 | train |
saltstack/salt | salt/modules/mac_timezone.py | list_zones | def list_zones():
'''
Displays a list of available time zones. Use this list when setting a
time zone using ``timezone.set_zone``
:return: a list of time zones
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' timezone.list_zones
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -listtimezones')
zones = salt.utils.mac_utils.parse_return(ret)
return [x.strip() for x in zones.splitlines()] | python | def list_zones():
'''
Displays a list of available time zones. Use this list when setting a
time zone using ``timezone.set_zone``
:return: a list of time zones
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' timezone.list_zones
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -listtimezones')
zones = salt.utils.mac_utils.parse_return(ret)
return [x.strip() for x in zones.splitlines()] | [
"def",
"list_zones",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -listtimezones'",
")",
"zones",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")",
"retur... | Displays a list of available time zones. Use this list when setting a
time zone using ``timezone.set_zone``
:return: a list of time zones
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' timezone.list_zones | [
"Displays",
"a",
"list",
"of",
"available",
"time",
"zones",
".",
"Use",
"this",
"list",
"when",
"setting",
"a",
"time",
"zone",
"using",
"timezone",
".",
"set_zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L201-L219 | train |
saltstack/salt | salt/modules/mac_timezone.py | set_zone | def set_zone(time_zone):
'''
Set the local time zone. Use ``timezone.list_zones`` to list valid time_zone
arguments
:param str time_zone: The time zone to apply
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Timezone
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone America/Denver
'''
if time_zone not in list_zones():
raise SaltInvocationError('Invalid Timezone: {0}'.format(time_zone))
salt.utils.mac_utils.execute_return_success(
'systemsetup -settimezone {0}'.format(time_zone))
return time_zone in get_zone() | python | def set_zone(time_zone):
'''
Set the local time zone. Use ``timezone.list_zones`` to list valid time_zone
arguments
:param str time_zone: The time zone to apply
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Timezone
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone America/Denver
'''
if time_zone not in list_zones():
raise SaltInvocationError('Invalid Timezone: {0}'.format(time_zone))
salt.utils.mac_utils.execute_return_success(
'systemsetup -settimezone {0}'.format(time_zone))
return time_zone in get_zone() | [
"def",
"set_zone",
"(",
"time_zone",
")",
":",
"if",
"time_zone",
"not",
"in",
"list_zones",
"(",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'Invalid Timezone: {0}'",
".",
"format",
"(",
"time_zone",
")",
")",
"salt",
".",
"utils",
".",
"mac_utils",
"."... | Set the local time zone. Use ``timezone.list_zones`` to list valid time_zone
arguments
:param str time_zone: The time zone to apply
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Timezone
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone America/Denver | [
"Set",
"the",
"local",
"time",
"zone",
".",
"Use",
"timezone",
".",
"list_zones",
"to",
"list",
"valid",
"time_zone",
"arguments"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L222-L247 | train |
saltstack/salt | salt/modules/mac_timezone.py | get_using_network_time | def get_using_network_time():
'''
Display whether network time is on or off
:return: True if network time is on, False if off
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' timezone.get_using_network_time
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getusingnetworktime')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | python | def get_using_network_time():
'''
Display whether network time is on or off
:return: True if network time is on, False if off
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' timezone.get_using_network_time
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getusingnetworktime')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | [
"def",
"get_using_network_time",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getusingnetworktime'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"salt"... | Display whether network time is on or off
:return: True if network time is on, False if off
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' timezone.get_using_network_time | [
"Display",
"whether",
"network",
"time",
"is",
"on",
"or",
"off"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L266-L283 | train |
saltstack/salt | salt/modules/mac_timezone.py | set_using_network_time | def set_using_network_time(enable):
'''
Set whether network time is on or off.
:param enable: True to enable, False to disable. Can also use 'on' or 'off'
:type: str bool
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_using_network_time True
'''
state = salt.utils.mac_utils.validate_enabled(enable)
cmd = 'systemsetup -setusingnetworktime {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return state == salt.utils.mac_utils.validate_enabled(
get_using_network_time()) | python | def set_using_network_time(enable):
'''
Set whether network time is on or off.
:param enable: True to enable, False to disable. Can also use 'on' or 'off'
:type: str bool
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_using_network_time True
'''
state = salt.utils.mac_utils.validate_enabled(enable)
cmd = 'systemsetup -setusingnetworktime {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return state == salt.utils.mac_utils.validate_enabled(
get_using_network_time()) | [
"def",
"set_using_network_time",
"(",
"enable",
")",
":",
"state",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"enable",
")",
"cmd",
"=",
"'systemsetup -setusingnetworktime {0}'",
".",
"format",
"(",
"state",
")",
"salt",
".",
"u... | Set whether network time is on or off.
:param enable: True to enable, False to disable. Can also use 'on' or 'off'
:type: str bool
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_using_network_time True | [
"Set",
"whether",
"network",
"time",
"is",
"on",
"or",
"off",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L286-L310 | train |
saltstack/salt | salt/modules/mac_timezone.py | get_time_server | def get_time_server():
'''
Display the currently set network time server.
:return: the network time server
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time_server
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getnetworktimeserver')
return salt.utils.mac_utils.parse_return(ret) | python | def get_time_server():
'''
Display the currently set network time server.
:return: the network time server
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time_server
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getnetworktimeserver')
return salt.utils.mac_utils.parse_return(ret) | [
"def",
"get_time_server",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getnetworktimeserver'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | Display the currently set network time server.
:return: the network time server
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time_server | [
"Display",
"the",
"currently",
"set",
"network",
"time",
"server",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L313-L328 | train |
saltstack/salt | salt/modules/mac_timezone.py | set_time_server | def set_time_server(time_server='time.apple.com'):
'''
Designates a network time server. Enter the IP address or DNS name for the
network time server.
:param time_server: IP or DNS name of the network time server. If nothing
is passed the time server will be set to the macOS default of
'time.apple.com'
:type: str
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_time_server time.acme.com
'''
cmd = 'systemsetup -setnetworktimeserver {0}'.format(time_server)
salt.utils.mac_utils.execute_return_success(cmd)
return time_server in get_time_server() | python | def set_time_server(time_server='time.apple.com'):
'''
Designates a network time server. Enter the IP address or DNS name for the
network time server.
:param time_server: IP or DNS name of the network time server. If nothing
is passed the time server will be set to the macOS default of
'time.apple.com'
:type: str
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_time_server time.acme.com
'''
cmd = 'systemsetup -setnetworktimeserver {0}'.format(time_server)
salt.utils.mac_utils.execute_return_success(cmd)
return time_server in get_time_server() | [
"def",
"set_time_server",
"(",
"time_server",
"=",
"'time.apple.com'",
")",
":",
"cmd",
"=",
"'systemsetup -setnetworktimeserver {0}'",
".",
"format",
"(",
"time_server",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
")",
... | Designates a network time server. Enter the IP address or DNS name for the
network time server.
:param time_server: IP or DNS name of the network time server. If nothing
is passed the time server will be set to the macOS default of
'time.apple.com'
:type: str
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_time_server time.acme.com | [
"Designates",
"a",
"network",
"time",
"server",
".",
"Enter",
"the",
"IP",
"address",
"or",
"DNS",
"name",
"for",
"the",
"network",
"time",
"server",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L331-L355 | train |
saltstack/salt | salt/modules/nexus.py | get_snapshot | def get_snapshot(nexus_url, repository, group_id, artifact_id, packaging, version, snapshot_version=None, target_dir='/tmp', target_file=None, classifier=None, username=None, password=None):
'''
Gets snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
'''
log.debug('======================== MODULE FUNCTION: nexus.get_snapshot(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, target_dir=%s, classifier=%s)',
nexus_url, repository, group_id, artifact_id, packaging, version, target_dir, classifier)
headers = {}
if username and password:
headers['Authorization'] = 'Basic {0}'.format(base64.encodestring('{0}:{1}'.format(username, password)).replace('\n', ''))
snapshot_url, file_name = _get_snapshot_url(nexus_url=nexus_url, repository=repository, group_id=group_id, artifact_id=artifact_id, version=version, packaging=packaging, snapshot_version=snapshot_version, classifier=classifier, headers=headers)
target_file = __resolve_target_file(file_name, target_dir, target_file)
return __save_artifact(snapshot_url, target_file, headers) | python | def get_snapshot(nexus_url, repository, group_id, artifact_id, packaging, version, snapshot_version=None, target_dir='/tmp', target_file=None, classifier=None, username=None, password=None):
'''
Gets snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
'''
log.debug('======================== MODULE FUNCTION: nexus.get_snapshot(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, target_dir=%s, classifier=%s)',
nexus_url, repository, group_id, artifact_id, packaging, version, target_dir, classifier)
headers = {}
if username and password:
headers['Authorization'] = 'Basic {0}'.format(base64.encodestring('{0}:{1}'.format(username, password)).replace('\n', ''))
snapshot_url, file_name = _get_snapshot_url(nexus_url=nexus_url, repository=repository, group_id=group_id, artifact_id=artifact_id, version=version, packaging=packaging, snapshot_version=snapshot_version, classifier=classifier, headers=headers)
target_file = __resolve_target_file(file_name, target_dir, target_file)
return __save_artifact(snapshot_url, target_file, headers) | [
"def",
"get_snapshot",
"(",
"nexus_url",
",",
"repository",
",",
"group_id",
",",
"artifact_id",
",",
"packaging",
",",
"version",
",",
"snapshot_version",
"=",
"None",
",",
"target_dir",
"=",
"'/tmp'",
",",
"target_file",
"=",
"None",
",",
"classifier",
"=",
... | Gets snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
target_dir
Target directory to download artifact to (default: /tmp)
target_file
Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging)
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter. | [
"Gets",
"snapshot",
"of",
"the",
"desired",
"version",
"of",
"the",
"artifact"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nexus.py#L83-L118 | train |
saltstack/salt | salt/modules/nexus.py | get_snapshot_version_string | def get_snapshot_version_string(nexus_url, repository, group_id, artifact_id, packaging, version, classifier=None, username=None, password=None):
'''
Gets the specific version string of a snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
'''
log.debug('======================== MODULE FUNCTION: nexus.get_snapshot_version_string(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, classifier=%s)',
nexus_url, repository, group_id, artifact_id, packaging, version, classifier)
headers = {}
if username and password:
headers['Authorization'] = 'Basic {0}'.format(base64.encodestring('{0}:{1}'.format(username, password)).replace('\n', ''))
return _get_snapshot_url(nexus_url=nexus_url, repository=repository, group_id=group_id, artifact_id=artifact_id, version=version, packaging=packaging, classifier=classifier, just_get_version_string=True) | python | def get_snapshot_version_string(nexus_url, repository, group_id, artifact_id, packaging, version, classifier=None, username=None, password=None):
'''
Gets the specific version string of a snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter.
'''
log.debug('======================== MODULE FUNCTION: nexus.get_snapshot_version_string(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, classifier=%s)',
nexus_url, repository, group_id, artifact_id, packaging, version, classifier)
headers = {}
if username and password:
headers['Authorization'] = 'Basic {0}'.format(base64.encodestring('{0}:{1}'.format(username, password)).replace('\n', ''))
return _get_snapshot_url(nexus_url=nexus_url, repository=repository, group_id=group_id, artifact_id=artifact_id, version=version, packaging=packaging, classifier=classifier, just_get_version_string=True) | [
"def",
"get_snapshot_version_string",
"(",
"nexus_url",
",",
"repository",
",",
"group_id",
",",
"artifact_id",
",",
"packaging",
",",
"version",
",",
"classifier",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"log",
"."... | Gets the specific version string of a snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the artifact
packaging
Packaging type (jar,war,ear,etc)
version
Version of the artifact
classifier
Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.
username
nexus username. Optional parameter.
password
nexus password. Optional parameter. | [
"Gets",
"the",
"specific",
"version",
"string",
"of",
"a",
"snapshot",
"of",
"the",
"desired",
"version",
"of",
"the",
"artifact"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nexus.py#L121-L149 | train |
saltstack/salt | salt/sdb/yaml.py | get | def get(key, profile=None): # pylint: disable=W0613
'''
Get a value from the dictionary
'''
data = _get_values(profile)
# Decrypt SDB data if specified in the profile
if profile and profile.get('gpg', False):
return salt.utils.data.traverse_dict_and_list(_decrypt(data), key, None)
return salt.utils.data.traverse_dict_and_list(data, key, None) | python | def get(key, profile=None): # pylint: disable=W0613
'''
Get a value from the dictionary
'''
data = _get_values(profile)
# Decrypt SDB data if specified in the profile
if profile and profile.get('gpg', False):
return salt.utils.data.traverse_dict_and_list(_decrypt(data), key, None)
return salt.utils.data.traverse_dict_and_list(data, key, None) | [
"def",
"get",
"(",
"key",
",",
"profile",
"=",
"None",
")",
":",
"# pylint: disable=W0613",
"data",
"=",
"_get_values",
"(",
"profile",
")",
"# Decrypt SDB data if specified in the profile",
"if",
"profile",
"and",
"profile",
".",
"get",
"(",
"'gpg'",
",",
"Fals... | Get a value from the dictionary | [
"Get",
"a",
"value",
"from",
"the",
"dictionary"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/yaml.py#L71-L81 | train |
saltstack/salt | salt/sdb/yaml.py | _get_values | def _get_values(profile=None):
'''
Retrieve all the referenced files, deserialize, then merge them together
'''
profile = profile or {}
serializers = salt.loader.serializers(__opts__)
ret = {}
for fname in profile.get('files', []):
try:
with salt.utils.files.flopen(fname) as yamlfile:
contents = serializers.yaml.deserialize(yamlfile)
ret = salt.utils.dictupdate.merge(
ret, contents, **profile.get('merge', {}))
except IOError:
log.error("File '%s' not found ", fname)
except TypeError as exc:
log.error("Error deserializing sdb file '%s': %s", fname, exc)
return ret | python | def _get_values(profile=None):
'''
Retrieve all the referenced files, deserialize, then merge them together
'''
profile = profile or {}
serializers = salt.loader.serializers(__opts__)
ret = {}
for fname in profile.get('files', []):
try:
with salt.utils.files.flopen(fname) as yamlfile:
contents = serializers.yaml.deserialize(yamlfile)
ret = salt.utils.dictupdate.merge(
ret, contents, **profile.get('merge', {}))
except IOError:
log.error("File '%s' not found ", fname)
except TypeError as exc:
log.error("Error deserializing sdb file '%s': %s", fname, exc)
return ret | [
"def",
"_get_values",
"(",
"profile",
"=",
"None",
")",
":",
"profile",
"=",
"profile",
"or",
"{",
"}",
"serializers",
"=",
"salt",
".",
"loader",
".",
"serializers",
"(",
"__opts__",
")",
"ret",
"=",
"{",
"}",
"for",
"fname",
"in",
"profile",
".",
"... | Retrieve all the referenced files, deserialize, then merge them together | [
"Retrieve",
"all",
"the",
"referenced",
"files",
"deserialize",
"then",
"merge",
"them",
"together"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/yaml.py#L84-L102 | train |
saltstack/salt | salt/states/zabbix_host.py | present | def present(host, groups, interfaces, **kwargs):
'''
Ensures that the host exists, eventually creates new host.
NOTE: please use argument visible_name instead of name to not mess with name from salt sls. This function accepts
all standard host properties: keyword argument names differ depending on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param proxy_host: Optional proxy name or proxyid to monitor host
:param inventory: Optional list of inventory names and values
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: Optional - string with visible name of the host, use 'visible_name' instead of 'name' \
parameter to not mess with value supplied from Salt sls file.
.. code-block:: yaml
create_test_host:
zabbix_host.present:
- host: TestHostWithInterfaces
- proxy_host: 12345
- groups:
- 5
- 6
- 7
- interfaces:
- test1.example.com:
- ip: '192.168.1.8'
- type: 'Agent'
- port: 92
- testing2_create:
- ip: '192.168.1.9'
- dns: 'test2.example.com'
- type: 'agent'
- main: false
- testovaci1_ipmi:
- ip: '192.168.100.111'
- type: 'ipmi'
- inventory:
- alias: some alias
- asset_tag: jlm3937
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_host_created = 'Host {0} created.'.format(host)
comment_host_updated = 'Host {0} updated.'.format(host)
comment_host_notcreated = 'Unable to create host: {0}. '.format(host)
comment_host_exists = 'Host {0} already exists.'.format(host)
changes_host_created = {host: {'old': 'Host {0} does not exist.'.format(host),
'new': 'Host {0} created.'.format(host),
}
}
def _interface_format(interfaces_data):
'''
Formats interfaces from SLS file into valid JSON usable for zabbix API.
Completes JSON with default values.
:param interfaces_data: list of interfaces data from SLS file
'''
if not interfaces_data:
return list()
interface_attrs = ('ip', 'dns', 'main', 'type', 'useip', 'port')
interfaces_json = loads(dumps(interfaces_data))
interfaces_dict = dict()
for interface in interfaces_json:
for intf in interface:
intf_name = intf
interfaces_dict[intf_name] = dict()
for intf_val in interface[intf]:
for key, value in intf_val.items():
if key in interface_attrs:
interfaces_dict[intf_name][key] = value
interfaces_list = list()
interface_ports = {'agent': ['1', '10050'], 'snmp': ['2', '161'], 'ipmi': ['3', '623'],
'jmx': ['4', '12345']}
for key, value in interfaces_dict.items():
# Load interface values or default values
interface_type = interface_ports[value['type'].lower()][0]
main = '1' if six.text_type(value.get('main', 'true')).lower() == 'true' else '0'
useip = '1' if six.text_type(value.get('useip', 'true')).lower() == 'true' else '0'
interface_ip = value.get('ip', '')
dns = value.get('dns', key)
port = six.text_type(value.get('port', interface_ports[value['type'].lower()][1]))
interfaces_list.append({'type': interface_type,
'main': main,
'useip': useip,
'ip': interface_ip,
'dns': dns,
'port': port})
interfaces_list = interfaces_list
interfaces_list_sorted = sorted(interfaces_list, key=lambda k: k['main'], reverse=True)
return interfaces_list_sorted
interfaces_formated = _interface_format(interfaces)
# Ensure groups are all groupid
groupids = []
for group in groups:
if isinstance(group, six.string_types):
groupid = __salt__['zabbix.hostgroup_get'](name=group, **connection_args)
try:
groupids.append(int(groupid[0]['groupid']))
except TypeError:
ret['comment'] = 'Invalid group {0}'.format(group)
return ret
else:
groupids.append(group)
groups = groupids
# Get and validate proxyid
proxy_hostid = "0"
if 'proxy_host' in kwargs:
# Test if proxy_host given as name
if isinstance(kwargs['proxy_host'], six.string_types):
try:
proxy_hostid = __salt__['zabbix.run_query']('proxy.get', {"output": "proxyid",
"selectInterface": "extend",
"filter": {"host": "{0}".format(kwargs['proxy_host'])}},
**connection_args)[0]['proxyid']
except TypeError:
ret['comment'] = 'Invalid proxy_host {0}'.format(kwargs['proxy_host'])
return ret
# Otherwise lookup proxy_host as proxyid
else:
try:
proxy_hostid = __salt__['zabbix.run_query']('proxy.get', {"proxyids":
"{0}".format(kwargs['proxy_host']),
"output": "proxyid"},
**connection_args)[0]['proxyid']
except TypeError:
ret['comment'] = 'Invalid proxy_host {0}'.format(kwargs['proxy_host'])
return ret
if 'inventory' not in kwargs:
inventory = {}
else:
inventory = kwargs['inventory']
if inventory is None:
inventory = {}
# Create dict of requested inventory items
new_inventory = {}
for inv_item in inventory:
for k, v in inv_item.items():
new_inventory[k] = str(v)
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if host_exists:
host = __salt__['zabbix.host_get'](host=host, **connection_args)[0]
hostid = host['hostid']
update_proxy = False
update_hostgroups = False
update_interfaces = False
update_inventory = False
cur_proxy_hostid = host['proxy_hostid']
if proxy_hostid != cur_proxy_hostid:
update_proxy = True
hostgroups = __salt__['zabbix.hostgroup_get'](hostids=hostid, **connection_args)
cur_hostgroups = list()
for hostgroup in hostgroups:
cur_hostgroups.append(int(hostgroup['groupid']))
if set(groups) != set(cur_hostgroups):
update_hostgroups = True
hostinterfaces = __salt__['zabbix.hostinterface_get'](hostids=hostid, **connection_args)
if hostinterfaces:
hostinterfaces = sorted(hostinterfaces, key=lambda k: k['main'])
hostinterfaces_copy = deepcopy(hostinterfaces)
for hostintf in hostinterfaces_copy:
hostintf.pop('interfaceid')
hostintf.pop('bulk')
hostintf.pop('hostid')
interface_diff = [x for x in interfaces_formated if x not in hostinterfaces_copy] + \
[y for y in hostinterfaces_copy if y not in interfaces_formated]
if interface_diff:
update_interfaces = True
elif not hostinterfaces and interfaces:
update_interfaces = True
cur_inventory = __salt__['zabbix.host_inventory_get'](hostids=hostid, **connection_args)
if cur_inventory:
# Remove blank inventory items
cur_inventory = {k: v for k, v in cur_inventory.items() if v}
# Remove persistent inventory keys for comparison
cur_inventory.pop('hostid', None)
cur_inventory.pop('inventory_mode', None)
if new_inventory and not cur_inventory:
update_inventory = True
elif set(cur_inventory) != set(new_inventory):
update_inventory = True
# Dry run, test=true mode
if __opts__['test']:
if host_exists:
if update_hostgroups or update_interfaces or update_proxy or update_inventory:
ret['result'] = None
ret['comment'] = comment_host_updated
else:
ret['result'] = True
ret['comment'] = comment_host_exists
else:
ret['result'] = None
ret['comment'] = comment_host_created
ret['changes'] = changes_host_created
return ret
error = []
if host_exists:
ret['result'] = True
if update_hostgroups or update_interfaces or update_proxy or update_inventory:
if update_inventory:
# combine connection_args, inventory, and clear_old
sum_kwargs = dict(new_inventory)
sum_kwargs.update(connection_args)
sum_kwargs['clear_old'] = True
hostupdate = __salt__['zabbix.host_inventory_set'](hostid, **sum_kwargs)
ret['changes']['inventory'] = str(new_inventory)
if 'error' in hostupdate:
error.append(hostupdate['error'])
if update_proxy:
hostupdate = __salt__['zabbix.host_update'](hostid, proxy_hostid=proxy_hostid, **connection_args)
ret['changes']['proxy_hostid'] = six.text_type(proxy_hostid)
if 'error' in hostupdate:
error.append(hostupdate['error'])
if update_hostgroups:
hostupdate = __salt__['zabbix.host_update'](hostid, groups=groups, **connection_args)
ret['changes']['groups'] = six.text_type(groups)
if 'error' in hostupdate:
error.append(hostupdate['error'])
if update_interfaces:
if hostinterfaces:
for interface in hostinterfaces:
__salt__['zabbix.hostinterface_delete'](interfaceids=interface['interfaceid'],
**connection_args)
hostid = __salt__['zabbix.host_get'](name=host, **connection_args)[0]['hostid']
for interface in interfaces_formated:
updatedint = __salt__['zabbix.hostinterface_create'](hostid=hostid,
ip=interface['ip'],
dns=interface['dns'],
main=interface['main'],
type=interface['type'],
useip=interface['useip'],
port=interface['port'],
**connection_args)
if 'error' in updatedint:
error.append(updatedint['error'])
ret['changes']['interfaces'] = six.text_type(interfaces_formated)
ret['comment'] = comment_host_updated
else:
ret['comment'] = comment_host_exists
else:
host_create = __salt__['zabbix.host_create'](host,
groups,
interfaces_formated,
proxy_hostid=proxy_hostid,
inventory=new_inventory,
**connection_args)
if 'error' not in host_create:
ret['result'] = True
ret['comment'] = comment_host_created
ret['changes'] = changes_host_created
else:
ret['result'] = False
ret['comment'] = comment_host_notcreated + six.text_type(host_create['error'])
# error detected
if error:
ret['changes'] = {}
ret['result'] = False
ret['comment'] = six.text_type(error)
return ret | python | def present(host, groups, interfaces, **kwargs):
'''
Ensures that the host exists, eventually creates new host.
NOTE: please use argument visible_name instead of name to not mess with name from salt sls. This function accepts
all standard host properties: keyword argument names differ depending on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param proxy_host: Optional proxy name or proxyid to monitor host
:param inventory: Optional list of inventory names and values
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: Optional - string with visible name of the host, use 'visible_name' instead of 'name' \
parameter to not mess with value supplied from Salt sls file.
.. code-block:: yaml
create_test_host:
zabbix_host.present:
- host: TestHostWithInterfaces
- proxy_host: 12345
- groups:
- 5
- 6
- 7
- interfaces:
- test1.example.com:
- ip: '192.168.1.8'
- type: 'Agent'
- port: 92
- testing2_create:
- ip: '192.168.1.9'
- dns: 'test2.example.com'
- type: 'agent'
- main: false
- testovaci1_ipmi:
- ip: '192.168.100.111'
- type: 'ipmi'
- inventory:
- alias: some alias
- asset_tag: jlm3937
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_host_created = 'Host {0} created.'.format(host)
comment_host_updated = 'Host {0} updated.'.format(host)
comment_host_notcreated = 'Unable to create host: {0}. '.format(host)
comment_host_exists = 'Host {0} already exists.'.format(host)
changes_host_created = {host: {'old': 'Host {0} does not exist.'.format(host),
'new': 'Host {0} created.'.format(host),
}
}
def _interface_format(interfaces_data):
'''
Formats interfaces from SLS file into valid JSON usable for zabbix API.
Completes JSON with default values.
:param interfaces_data: list of interfaces data from SLS file
'''
if not interfaces_data:
return list()
interface_attrs = ('ip', 'dns', 'main', 'type', 'useip', 'port')
interfaces_json = loads(dumps(interfaces_data))
interfaces_dict = dict()
for interface in interfaces_json:
for intf in interface:
intf_name = intf
interfaces_dict[intf_name] = dict()
for intf_val in interface[intf]:
for key, value in intf_val.items():
if key in interface_attrs:
interfaces_dict[intf_name][key] = value
interfaces_list = list()
interface_ports = {'agent': ['1', '10050'], 'snmp': ['2', '161'], 'ipmi': ['3', '623'],
'jmx': ['4', '12345']}
for key, value in interfaces_dict.items():
# Load interface values or default values
interface_type = interface_ports[value['type'].lower()][0]
main = '1' if six.text_type(value.get('main', 'true')).lower() == 'true' else '0'
useip = '1' if six.text_type(value.get('useip', 'true')).lower() == 'true' else '0'
interface_ip = value.get('ip', '')
dns = value.get('dns', key)
port = six.text_type(value.get('port', interface_ports[value['type'].lower()][1]))
interfaces_list.append({'type': interface_type,
'main': main,
'useip': useip,
'ip': interface_ip,
'dns': dns,
'port': port})
interfaces_list = interfaces_list
interfaces_list_sorted = sorted(interfaces_list, key=lambda k: k['main'], reverse=True)
return interfaces_list_sorted
interfaces_formated = _interface_format(interfaces)
# Ensure groups are all groupid
groupids = []
for group in groups:
if isinstance(group, six.string_types):
groupid = __salt__['zabbix.hostgroup_get'](name=group, **connection_args)
try:
groupids.append(int(groupid[0]['groupid']))
except TypeError:
ret['comment'] = 'Invalid group {0}'.format(group)
return ret
else:
groupids.append(group)
groups = groupids
# Get and validate proxyid
proxy_hostid = "0"
if 'proxy_host' in kwargs:
# Test if proxy_host given as name
if isinstance(kwargs['proxy_host'], six.string_types):
try:
proxy_hostid = __salt__['zabbix.run_query']('proxy.get', {"output": "proxyid",
"selectInterface": "extend",
"filter": {"host": "{0}".format(kwargs['proxy_host'])}},
**connection_args)[0]['proxyid']
except TypeError:
ret['comment'] = 'Invalid proxy_host {0}'.format(kwargs['proxy_host'])
return ret
# Otherwise lookup proxy_host as proxyid
else:
try:
proxy_hostid = __salt__['zabbix.run_query']('proxy.get', {"proxyids":
"{0}".format(kwargs['proxy_host']),
"output": "proxyid"},
**connection_args)[0]['proxyid']
except TypeError:
ret['comment'] = 'Invalid proxy_host {0}'.format(kwargs['proxy_host'])
return ret
if 'inventory' not in kwargs:
inventory = {}
else:
inventory = kwargs['inventory']
if inventory is None:
inventory = {}
# Create dict of requested inventory items
new_inventory = {}
for inv_item in inventory:
for k, v in inv_item.items():
new_inventory[k] = str(v)
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if host_exists:
host = __salt__['zabbix.host_get'](host=host, **connection_args)[0]
hostid = host['hostid']
update_proxy = False
update_hostgroups = False
update_interfaces = False
update_inventory = False
cur_proxy_hostid = host['proxy_hostid']
if proxy_hostid != cur_proxy_hostid:
update_proxy = True
hostgroups = __salt__['zabbix.hostgroup_get'](hostids=hostid, **connection_args)
cur_hostgroups = list()
for hostgroup in hostgroups:
cur_hostgroups.append(int(hostgroup['groupid']))
if set(groups) != set(cur_hostgroups):
update_hostgroups = True
hostinterfaces = __salt__['zabbix.hostinterface_get'](hostids=hostid, **connection_args)
if hostinterfaces:
hostinterfaces = sorted(hostinterfaces, key=lambda k: k['main'])
hostinterfaces_copy = deepcopy(hostinterfaces)
for hostintf in hostinterfaces_copy:
hostintf.pop('interfaceid')
hostintf.pop('bulk')
hostintf.pop('hostid')
interface_diff = [x for x in interfaces_formated if x not in hostinterfaces_copy] + \
[y for y in hostinterfaces_copy if y not in interfaces_formated]
if interface_diff:
update_interfaces = True
elif not hostinterfaces and interfaces:
update_interfaces = True
cur_inventory = __salt__['zabbix.host_inventory_get'](hostids=hostid, **connection_args)
if cur_inventory:
# Remove blank inventory items
cur_inventory = {k: v for k, v in cur_inventory.items() if v}
# Remove persistent inventory keys for comparison
cur_inventory.pop('hostid', None)
cur_inventory.pop('inventory_mode', None)
if new_inventory and not cur_inventory:
update_inventory = True
elif set(cur_inventory) != set(new_inventory):
update_inventory = True
# Dry run, test=true mode
if __opts__['test']:
if host_exists:
if update_hostgroups or update_interfaces or update_proxy or update_inventory:
ret['result'] = None
ret['comment'] = comment_host_updated
else:
ret['result'] = True
ret['comment'] = comment_host_exists
else:
ret['result'] = None
ret['comment'] = comment_host_created
ret['changes'] = changes_host_created
return ret
error = []
if host_exists:
ret['result'] = True
if update_hostgroups or update_interfaces or update_proxy or update_inventory:
if update_inventory:
# combine connection_args, inventory, and clear_old
sum_kwargs = dict(new_inventory)
sum_kwargs.update(connection_args)
sum_kwargs['clear_old'] = True
hostupdate = __salt__['zabbix.host_inventory_set'](hostid, **sum_kwargs)
ret['changes']['inventory'] = str(new_inventory)
if 'error' in hostupdate:
error.append(hostupdate['error'])
if update_proxy:
hostupdate = __salt__['zabbix.host_update'](hostid, proxy_hostid=proxy_hostid, **connection_args)
ret['changes']['proxy_hostid'] = six.text_type(proxy_hostid)
if 'error' in hostupdate:
error.append(hostupdate['error'])
if update_hostgroups:
hostupdate = __salt__['zabbix.host_update'](hostid, groups=groups, **connection_args)
ret['changes']['groups'] = six.text_type(groups)
if 'error' in hostupdate:
error.append(hostupdate['error'])
if update_interfaces:
if hostinterfaces:
for interface in hostinterfaces:
__salt__['zabbix.hostinterface_delete'](interfaceids=interface['interfaceid'],
**connection_args)
hostid = __salt__['zabbix.host_get'](name=host, **connection_args)[0]['hostid']
for interface in interfaces_formated:
updatedint = __salt__['zabbix.hostinterface_create'](hostid=hostid,
ip=interface['ip'],
dns=interface['dns'],
main=interface['main'],
type=interface['type'],
useip=interface['useip'],
port=interface['port'],
**connection_args)
if 'error' in updatedint:
error.append(updatedint['error'])
ret['changes']['interfaces'] = six.text_type(interfaces_formated)
ret['comment'] = comment_host_updated
else:
ret['comment'] = comment_host_exists
else:
host_create = __salt__['zabbix.host_create'](host,
groups,
interfaces_formated,
proxy_hostid=proxy_hostid,
inventory=new_inventory,
**connection_args)
if 'error' not in host_create:
ret['result'] = True
ret['comment'] = comment_host_created
ret['changes'] = changes_host_created
else:
ret['result'] = False
ret['comment'] = comment_host_notcreated + six.text_type(host_create['error'])
# error detected
if error:
ret['changes'] = {}
ret['result'] = False
ret['comment'] = six.text_type(error)
return ret | [
"def",
"present",
"(",
"host",
",",
"groups",
",",
"interfaces",
",",
"*",
"*",
"kwargs",
")",
":",
"connection_args",
"=",
"{",
"}",
"if",
"'_connection_user'",
"in",
"kwargs",
":",
"connection_args",
"[",
"'_connection_user'",
"]",
"=",
"kwargs",
"[",
"'... | Ensures that the host exists, eventually creates new host.
NOTE: please use argument visible_name instead of name to not mess with name from salt sls. This function accepts
all standard host properties: keyword argument names differ depending on your zabbix version, see:
https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param groups: groupids of host groups to add the host to
:param interfaces: interfaces to be created for the host
:param proxy_host: Optional proxy name or proxyid to monitor host
:param inventory: Optional list of inventory names and values
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
:param visible_name: Optional - string with visible name of the host, use 'visible_name' instead of 'name' \
parameter to not mess with value supplied from Salt sls file.
.. code-block:: yaml
create_test_host:
zabbix_host.present:
- host: TestHostWithInterfaces
- proxy_host: 12345
- groups:
- 5
- 6
- 7
- interfaces:
- test1.example.com:
- ip: '192.168.1.8'
- type: 'Agent'
- port: 92
- testing2_create:
- ip: '192.168.1.9'
- dns: 'test2.example.com'
- type: 'agent'
- main: false
- testovaci1_ipmi:
- ip: '192.168.100.111'
- type: 'ipmi'
- inventory:
- alias: some alias
- asset_tag: jlm3937 | [
"Ensures",
"that",
"the",
"host",
"exists",
"eventually",
"creates",
"new",
"host",
".",
"NOTE",
":",
"please",
"use",
"argument",
"visible_name",
"instead",
"of",
"name",
"to",
"not",
"mess",
"with",
"name",
"from",
"salt",
"sls",
".",
"This",
"function",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_host.py#L22-L337 | train |
saltstack/salt | salt/states/zabbix_host.py | absent | def absent(name, **kwargs):
"""
Ensures that the host does not exists, eventually deletes host.
.. versionadded:: 2016.3.0
:param: name: technical name of the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
TestHostWithInterfaces:
zabbix_host.absent
"""
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_host_deleted = 'Host {0} deleted.'.format(name)
comment_host_notdeleted = 'Unable to delete host: {0}. '.format(name)
comment_host_notexists = 'Host {0} does not exist.'.format(name)
changes_host_deleted = {name: {'old': 'Host {0} exists.'.format(name),
'new': 'Host {0} deleted.'.format(name),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
host_exists = __salt__['zabbix.host_exists'](name, **connection_args)
# Dry run, test=true mode
if __opts__['test']:
if not host_exists:
ret['result'] = True
ret['comment'] = comment_host_notexists
else:
ret['result'] = None
ret['comment'] = comment_host_deleted
return ret
host_get = __salt__['zabbix.host_get'](name, **connection_args)
if not host_get:
ret['result'] = True
ret['comment'] = comment_host_notexists
else:
try:
hostid = host_get[0]['hostid']
host_delete = __salt__['zabbix.host_delete'](hostid, **connection_args)
except KeyError:
host_delete = False
if host_delete and 'error' not in host_delete:
ret['result'] = True
ret['comment'] = comment_host_deleted
ret['changes'] = changes_host_deleted
else:
ret['result'] = False
ret['comment'] = comment_host_notdeleted + six.text_type(host_delete['error'])
return ret | python | def absent(name, **kwargs):
"""
Ensures that the host does not exists, eventually deletes host.
.. versionadded:: 2016.3.0
:param: name: technical name of the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
TestHostWithInterfaces:
zabbix_host.absent
"""
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_host_deleted = 'Host {0} deleted.'.format(name)
comment_host_notdeleted = 'Unable to delete host: {0}. '.format(name)
comment_host_notexists = 'Host {0} does not exist.'.format(name)
changes_host_deleted = {name: {'old': 'Host {0} exists.'.format(name),
'new': 'Host {0} deleted.'.format(name),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
host_exists = __salt__['zabbix.host_exists'](name, **connection_args)
# Dry run, test=true mode
if __opts__['test']:
if not host_exists:
ret['result'] = True
ret['comment'] = comment_host_notexists
else:
ret['result'] = None
ret['comment'] = comment_host_deleted
return ret
host_get = __salt__['zabbix.host_get'](name, **connection_args)
if not host_get:
ret['result'] = True
ret['comment'] = comment_host_notexists
else:
try:
hostid = host_get[0]['hostid']
host_delete = __salt__['zabbix.host_delete'](hostid, **connection_args)
except KeyError:
host_delete = False
if host_delete and 'error' not in host_delete:
ret['result'] = True
ret['comment'] = comment_host_deleted
ret['changes'] = changes_host_deleted
else:
ret['result'] = False
ret['comment'] = comment_host_notdeleted + six.text_type(host_delete['error'])
return ret | [
"def",
"absent",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"# Comment and change messages",
"comment_host_dele... | Ensures that the host does not exists, eventually deletes host.
.. versionadded:: 2016.3.0
:param: name: technical name of the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
TestHostWithInterfaces:
zabbix_host.absent | [
"Ensures",
"that",
"the",
"host",
"does",
"not",
"exists",
"eventually",
"deletes",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_host.py#L340-L407 | train |
saltstack/salt | salt/states/zabbix_host.py | assign_templates | def assign_templates(host, templates, **kwargs):
'''
Ensures that templates are assigned to the host.
.. versionadded:: 2017.7.0
:param host: technical name of the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
add_zabbix_templates_to_host:
zabbix_host.assign_templates:
- host: TestHost
- templates:
- "Template OS Linux"
- "Template App MySQL"
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
# Set comments
comment_host_templates_updated = 'Templates updated.'
comment_host_templ_notupdated = 'Unable to update templates on host: {0}.'.format(host)
comment_host_templates_in_sync = 'Templates already synced.'
update_host_templates = False
curr_template_ids = list()
requested_template_ids = list()
hostid = ''
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
# Fail out if host does not exist
if not host_exists:
ret['result'] = False
ret['comment'] = comment_host_templ_notupdated
return ret
host_info = __salt__['zabbix.host_get'](host=host, **connection_args)[0]
hostid = host_info['hostid']
if not templates:
templates = list()
# Get current templateids for host
host_templates = __salt__['zabbix.host_get'](hostids=hostid,
output='[{"hostid"}]',
selectParentTemplates='["templateid"]',
**connection_args)
for template_id in host_templates[0]['parentTemplates']:
curr_template_ids.append(template_id['templateid'])
# Get requested templateids
for template in templates:
try:
template_id = __salt__['zabbix.template_get'](host=template, **connection_args)[0]['templateid']
requested_template_ids.append(template_id)
except TypeError:
ret['result'] = False
ret['comment'] = 'Unable to find template: {0}.'.format(template)
return ret
# remove any duplications
requested_template_ids = list(set(requested_template_ids))
if set(curr_template_ids) != set(requested_template_ids):
update_host_templates = True
# Set change output
changes_host_templates_modified = {host: {'old': 'Host templates: ' + ", ".join(curr_template_ids),
'new': 'Host templates: ' + ', '.join(requested_template_ids)}}
# Dry run, test=true mode
if __opts__['test']:
if update_host_templates:
ret['result'] = None
ret['comment'] = comment_host_templates_updated
else:
ret['result'] = True
ret['comment'] = comment_host_templates_in_sync
return ret
# Attempt to perform update
ret['result'] = True
if update_host_templates:
update_output = __salt__['zabbix.host_update'](hostid, templates=(requested_template_ids), **connection_args)
if update_output is False:
ret['result'] = False
ret['comment'] = comment_host_templ_notupdated
return ret
ret['comment'] = comment_host_templates_updated
ret['changes'] = changes_host_templates_modified
else:
ret['comment'] = comment_host_templates_in_sync
return ret | python | def assign_templates(host, templates, **kwargs):
'''
Ensures that templates are assigned to the host.
.. versionadded:: 2017.7.0
:param host: technical name of the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
add_zabbix_templates_to_host:
zabbix_host.assign_templates:
- host: TestHost
- templates:
- "Template OS Linux"
- "Template App MySQL"
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
# Set comments
comment_host_templates_updated = 'Templates updated.'
comment_host_templ_notupdated = 'Unable to update templates on host: {0}.'.format(host)
comment_host_templates_in_sync = 'Templates already synced.'
update_host_templates = False
curr_template_ids = list()
requested_template_ids = list()
hostid = ''
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
# Fail out if host does not exist
if not host_exists:
ret['result'] = False
ret['comment'] = comment_host_templ_notupdated
return ret
host_info = __salt__['zabbix.host_get'](host=host, **connection_args)[0]
hostid = host_info['hostid']
if not templates:
templates = list()
# Get current templateids for host
host_templates = __salt__['zabbix.host_get'](hostids=hostid,
output='[{"hostid"}]',
selectParentTemplates='["templateid"]',
**connection_args)
for template_id in host_templates[0]['parentTemplates']:
curr_template_ids.append(template_id['templateid'])
# Get requested templateids
for template in templates:
try:
template_id = __salt__['zabbix.template_get'](host=template, **connection_args)[0]['templateid']
requested_template_ids.append(template_id)
except TypeError:
ret['result'] = False
ret['comment'] = 'Unable to find template: {0}.'.format(template)
return ret
# remove any duplications
requested_template_ids = list(set(requested_template_ids))
if set(curr_template_ids) != set(requested_template_ids):
update_host_templates = True
# Set change output
changes_host_templates_modified = {host: {'old': 'Host templates: ' + ", ".join(curr_template_ids),
'new': 'Host templates: ' + ', '.join(requested_template_ids)}}
# Dry run, test=true mode
if __opts__['test']:
if update_host_templates:
ret['result'] = None
ret['comment'] = comment_host_templates_updated
else:
ret['result'] = True
ret['comment'] = comment_host_templates_in_sync
return ret
# Attempt to perform update
ret['result'] = True
if update_host_templates:
update_output = __salt__['zabbix.host_update'](hostid, templates=(requested_template_ids), **connection_args)
if update_output is False:
ret['result'] = False
ret['comment'] = comment_host_templ_notupdated
return ret
ret['comment'] = comment_host_templates_updated
ret['changes'] = changes_host_templates_modified
else:
ret['comment'] = comment_host_templates_in_sync
return ret | [
"def",
"assign_templates",
"(",
"host",
",",
"templates",
",",
"*",
"*",
"kwargs",
")",
":",
"connection_args",
"=",
"{",
"}",
"if",
"'_connection_user'",
"in",
"kwargs",
":",
"connection_args",
"[",
"'_connection_user'",
"]",
"=",
"kwargs",
"[",
"'_connection... | Ensures that templates are assigned to the host.
.. versionadded:: 2017.7.0
:param host: technical name of the host
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
add_zabbix_templates_to_host:
zabbix_host.assign_templates:
- host: TestHost
- templates:
- "Template OS Linux"
- "Template App MySQL" | [
"Ensures",
"that",
"templates",
"are",
"assigned",
"to",
"the",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_host.py#L410-L516 | train |
saltstack/salt | salt/proxy/cimc.py | init | def init(opts):
'''
This function gets called when the proxy starts up.
'''
if 'host' not in opts['proxy']:
log.critical('No \'host\' key found in pillar for this proxy.')
return False
if 'username' not in opts['proxy']:
log.critical('No \'username\' key found in pillar for this proxy.')
return False
if 'password' not in opts['proxy']:
log.critical('No \'passwords\' key found in pillar for this proxy.')
return False
DETAILS['url'] = 'https://{0}/nuova'.format(opts['proxy']['host'])
DETAILS['headers'] = {'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 62,
'USER-Agent': 'lwp-request/2.06'}
# Set configuration details
DETAILS['host'] = opts['proxy']['host']
DETAILS['username'] = opts['proxy'].get('username')
DETAILS['password'] = opts['proxy'].get('password')
# Ensure connectivity to the device
log.debug("Attempting to connect to cimc proxy host.")
get_config_resolver_class("computeRackUnit")
log.debug("Successfully connected to cimc proxy host.")
DETAILS['initialized'] = True | python | def init(opts):
'''
This function gets called when the proxy starts up.
'''
if 'host' not in opts['proxy']:
log.critical('No \'host\' key found in pillar for this proxy.')
return False
if 'username' not in opts['proxy']:
log.critical('No \'username\' key found in pillar for this proxy.')
return False
if 'password' not in opts['proxy']:
log.critical('No \'passwords\' key found in pillar for this proxy.')
return False
DETAILS['url'] = 'https://{0}/nuova'.format(opts['proxy']['host'])
DETAILS['headers'] = {'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 62,
'USER-Agent': 'lwp-request/2.06'}
# Set configuration details
DETAILS['host'] = opts['proxy']['host']
DETAILS['username'] = opts['proxy'].get('username')
DETAILS['password'] = opts['proxy'].get('password')
# Ensure connectivity to the device
log.debug("Attempting to connect to cimc proxy host.")
get_config_resolver_class("computeRackUnit")
log.debug("Successfully connected to cimc proxy host.")
DETAILS['initialized'] = True | [
"def",
"init",
"(",
"opts",
")",
":",
"if",
"'host'",
"not",
"in",
"opts",
"[",
"'proxy'",
"]",
":",
"log",
".",
"critical",
"(",
"'No \\'host\\' key found in pillar for this proxy.'",
")",
"return",
"False",
"if",
"'username'",
"not",
"in",
"opts",
"[",
"'p... | This function gets called when the proxy starts up. | [
"This",
"function",
"gets",
"called",
"when",
"the",
"proxy",
"starts",
"up",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cimc.py#L110-L139 | train |
saltstack/salt | salt/proxy/cimc.py | set_config_modify | def set_config_modify(dn=None, inconfig=None, hierarchical=False):
'''
The configConfMo method configures the specified managed object in a single subtree (for example, DN).
'''
ret = {}
cookie = logon()
# Declare if the search contains hierarchical results.
h = "false"
if hierarchical is True:
h = "true"
payload = '<configConfMo cookie="{0}" inHierarchical="{1}" dn="{2}">' \
'<inConfig>{3}</inConfig></configConfMo>'.format(cookie, h, dn, inconfig)
r = __utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
raise_error=True,
status=True,
headers=DETAILS['headers'])
_validate_response_code(r['status'], cookie)
answer = re.findall(r'(<[\s\S.]*>)', r['text'])[0]
items = ET.fromstring(answer)
logout(cookie)
for item in items:
ret[item.tag] = prepare_return(item)
return ret | python | def set_config_modify(dn=None, inconfig=None, hierarchical=False):
'''
The configConfMo method configures the specified managed object in a single subtree (for example, DN).
'''
ret = {}
cookie = logon()
# Declare if the search contains hierarchical results.
h = "false"
if hierarchical is True:
h = "true"
payload = '<configConfMo cookie="{0}" inHierarchical="{1}" dn="{2}">' \
'<inConfig>{3}</inConfig></configConfMo>'.format(cookie, h, dn, inconfig)
r = __utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
raise_error=True,
status=True,
headers=DETAILS['headers'])
_validate_response_code(r['status'], cookie)
answer = re.findall(r'(<[\s\S.]*>)', r['text'])[0]
items = ET.fromstring(answer)
logout(cookie)
for item in items:
ret[item.tag] = prepare_return(item)
return ret | [
"def",
"set_config_modify",
"(",
"dn",
"=",
"None",
",",
"inconfig",
"=",
"None",
",",
"hierarchical",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"}",
"cookie",
"=",
"logon",
"(",
")",
"# Declare if the search contains hierarchical results.",
"h",
"=",
"\"false\... | The configConfMo method configures the specified managed object in a single subtree (for example, DN). | [
"The",
"configConfMo",
"method",
"configures",
"the",
"specified",
"managed",
"object",
"in",
"a",
"single",
"subtree",
"(",
"for",
"example",
"DN",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cimc.py#L142-L173 | train |
saltstack/salt | salt/proxy/cimc.py | logon | def logon():
'''
Logs into the cimc device and returns the session cookie.
'''
content = {}
payload = "<aaaLogin inName='{0}' inPassword='{1}'></aaaLogin>".format(DETAILS['username'], DETAILS['password'])
r = __utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
raise_error=False,
status=True,
headers=DETAILS['headers'])
_validate_response_code(r['status'])
answer = re.findall(r'(<[\s\S.]*>)', r['text'])[0]
items = ET.fromstring(answer)
for item in items.attrib:
content[item] = items.attrib[item]
if 'outCookie' not in content:
raise salt.exceptions.CommandExecutionError("Unable to log into proxy device.")
return content['outCookie'] | python | def logon():
'''
Logs into the cimc device and returns the session cookie.
'''
content = {}
payload = "<aaaLogin inName='{0}' inPassword='{1}'></aaaLogin>".format(DETAILS['username'], DETAILS['password'])
r = __utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
raise_error=False,
status=True,
headers=DETAILS['headers'])
_validate_response_code(r['status'])
answer = re.findall(r'(<[\s\S.]*>)', r['text'])[0]
items = ET.fromstring(answer)
for item in items.attrib:
content[item] = items.attrib[item]
if 'outCookie' not in content:
raise salt.exceptions.CommandExecutionError("Unable to log into proxy device.")
return content['outCookie'] | [
"def",
"logon",
"(",
")",
":",
"content",
"=",
"{",
"}",
"payload",
"=",
"\"<aaaLogin inName='{0}' inPassword='{1}'></aaaLogin>\"",
".",
"format",
"(",
"DETAILS",
"[",
"'username'",
"]",
",",
"DETAILS",
"[",
"'password'",
"]",
")",
"r",
"=",
"__utils__",
"[",
... | Logs into the cimc device and returns the session cookie. | [
"Logs",
"into",
"the",
"cimc",
"device",
"and",
"returns",
"the",
"session",
"cookie",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cimc.py#L210-L236 | train |
saltstack/salt | salt/proxy/cimc.py | logout | def logout(cookie=None):
'''
Closes the session with the device.
'''
payload = '<aaaLogout cookie="{0}" inCookie="{0}"></aaaLogout>'.format(cookie)
__utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
raise_error=True,
headers=DETAILS['headers'])
return | python | def logout(cookie=None):
'''
Closes the session with the device.
'''
payload = '<aaaLogout cookie="{0}" inCookie="{0}"></aaaLogout>'.format(cookie)
__utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
raise_error=True,
headers=DETAILS['headers'])
return | [
"def",
"logout",
"(",
"cookie",
"=",
"None",
")",
":",
"payload",
"=",
"'<aaaLogout cookie=\"{0}\" inCookie=\"{0}\"></aaaLogout>'",
".",
"format",
"(",
"cookie",
")",
"__utils__",
"[",
"'http.query'",
"]",
"(",
"DETAILS",
"[",
"'url'",
"]",
",",
"data",
"=",
"... | Closes the session with the device. | [
"Closes",
"the",
"session",
"with",
"the",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cimc.py#L239-L252 | train |
saltstack/salt | salt/proxy/cimc.py | prepare_return | def prepare_return(x):
'''
Converts the etree to dict
'''
ret = {}
for a in list(x):
if a.tag not in ret:
ret[a.tag] = []
ret[a.tag].append(prepare_return(a))
for a in x.attrib:
ret[a] = x.attrib[a]
return ret | python | def prepare_return(x):
'''
Converts the etree to dict
'''
ret = {}
for a in list(x):
if a.tag not in ret:
ret[a.tag] = []
ret[a.tag].append(prepare_return(a))
for a in x.attrib:
ret[a] = x.attrib[a]
return ret | [
"def",
"prepare_return",
"(",
"x",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"a",
"in",
"list",
"(",
"x",
")",
":",
"if",
"a",
".",
"tag",
"not",
"in",
"ret",
":",
"ret",
"[",
"a",
".",
"tag",
"]",
"=",
"[",
"]",
"ret",
"[",
"a",
".",
"tag",... | Converts the etree to dict | [
"Converts",
"the",
"etree",
"to",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cimc.py#L255-L266 | train |
saltstack/salt | salt/proxy/cimc.py | grains | def grains():
'''
Get the grains from the proxied device
'''
if not DETAILS.get('grains_cache', {}):
DETAILS['grains_cache'] = GRAINS_CACHE
try:
compute_rack = get_config_resolver_class('computeRackUnit', False)
DETAILS['grains_cache'] = compute_rack['outConfigs']['computeRackUnit']
except salt.exceptions.CommandExecutionError:
pass
except Exception as err:
log.error(err)
return DETAILS['grains_cache'] | python | def grains():
'''
Get the grains from the proxied device
'''
if not DETAILS.get('grains_cache', {}):
DETAILS['grains_cache'] = GRAINS_CACHE
try:
compute_rack = get_config_resolver_class('computeRackUnit', False)
DETAILS['grains_cache'] = compute_rack['outConfigs']['computeRackUnit']
except salt.exceptions.CommandExecutionError:
pass
except Exception as err:
log.error(err)
return DETAILS['grains_cache'] | [
"def",
"grains",
"(",
")",
":",
"if",
"not",
"DETAILS",
".",
"get",
"(",
"'grains_cache'",
",",
"{",
"}",
")",
":",
"DETAILS",
"[",
"'grains_cache'",
"]",
"=",
"GRAINS_CACHE",
"try",
":",
"compute_rack",
"=",
"get_config_resolver_class",
"(",
"'computeRackUn... | Get the grains from the proxied device | [
"Get",
"the",
"grains",
"from",
"the",
"proxied",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cimc.py#L278-L291 | train |
saltstack/salt | salt/proxy/cimc.py | ping | def ping():
'''
Returns true if the device is reachable, else false.
'''
try:
cookie = logon()
logout(cookie)
except salt.exceptions.CommandExecutionError:
return False
except Exception as err:
log.debug(err)
return False
return True | python | def ping():
'''
Returns true if the device is reachable, else false.
'''
try:
cookie = logon()
logout(cookie)
except salt.exceptions.CommandExecutionError:
return False
except Exception as err:
log.debug(err)
return False
return True | [
"def",
"ping",
"(",
")",
":",
"try",
":",
"cookie",
"=",
"logon",
"(",
")",
"logout",
"(",
"cookie",
")",
"except",
"salt",
".",
"exceptions",
".",
"CommandExecutionError",
":",
"return",
"False",
"except",
"Exception",
"as",
"err",
":",
"log",
".",
"d... | Returns true if the device is reachable, else false. | [
"Returns",
"true",
"if",
"the",
"device",
"is",
"reachable",
"else",
"false",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cimc.py#L302-L314 | train |
saltstack/salt | salt/utils/files.py | guess_archive_type | def guess_archive_type(name):
'''
Guess an archive type (tar, zip, or rar) by its file extension
'''
name = name.lower()
for ending in ('tar', 'tar.gz', 'tgz',
'tar.bz2', 'tbz2', 'tbz',
'tar.xz', 'txz',
'tar.lzma', 'tlz'):
if name.endswith('.' + ending):
return 'tar'
for ending in ('zip', 'rar'):
if name.endswith('.' + ending):
return ending
return None | python | def guess_archive_type(name):
'''
Guess an archive type (tar, zip, or rar) by its file extension
'''
name = name.lower()
for ending in ('tar', 'tar.gz', 'tgz',
'tar.bz2', 'tbz2', 'tbz',
'tar.xz', 'txz',
'tar.lzma', 'tlz'):
if name.endswith('.' + ending):
return 'tar'
for ending in ('zip', 'rar'):
if name.endswith('.' + ending):
return ending
return None | [
"def",
"guess_archive_type",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"for",
"ending",
"in",
"(",
"'tar'",
",",
"'tar.gz'",
",",
"'tgz'",
",",
"'tar.bz2'",
",",
"'tbz2'",
",",
"'tbz'",
",",
"'tar.xz'",
",",
"'txz'",
",",
"'... | Guess an archive type (tar, zip, or rar) by its file extension | [
"Guess",
"an",
"archive",
"type",
"(",
"tar",
"zip",
"or",
"rar",
")",
"by",
"its",
"file",
"extension"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L68-L82 | train |
saltstack/salt | salt/utils/files.py | mkstemp | def mkstemp(*args, **kwargs):
'''
Helper function which does exactly what ``tempfile.mkstemp()`` does but
accepts another argument, ``close_fd``, which, by default, is true and closes
the fd before returning the file path. Something commonly done throughout
Salt's code.
'''
if 'prefix' not in kwargs:
kwargs['prefix'] = '__salt.tmp.'
close_fd = kwargs.pop('close_fd', True)
fd_, f_path = tempfile.mkstemp(*args, **kwargs)
if close_fd is False:
return fd_, f_path
os.close(fd_)
del fd_
return f_path | python | def mkstemp(*args, **kwargs):
'''
Helper function which does exactly what ``tempfile.mkstemp()`` does but
accepts another argument, ``close_fd``, which, by default, is true and closes
the fd before returning the file path. Something commonly done throughout
Salt's code.
'''
if 'prefix' not in kwargs:
kwargs['prefix'] = '__salt.tmp.'
close_fd = kwargs.pop('close_fd', True)
fd_, f_path = tempfile.mkstemp(*args, **kwargs)
if close_fd is False:
return fd_, f_path
os.close(fd_)
del fd_
return f_path | [
"def",
"mkstemp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'prefix'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'prefix'",
"]",
"=",
"'__salt.tmp.'",
"close_fd",
"=",
"kwargs",
".",
"pop",
"(",
"'close_fd'",
",",
"True",
")",
"fd... | Helper function which does exactly what ``tempfile.mkstemp()`` does but
accepts another argument, ``close_fd``, which, by default, is true and closes
the fd before returning the file path. Something commonly done throughout
Salt's code. | [
"Helper",
"function",
"which",
"does",
"exactly",
"what",
"tempfile",
".",
"mkstemp",
"()",
"does",
"but",
"accepts",
"another",
"argument",
"close_fd",
"which",
"by",
"default",
"is",
"true",
"and",
"closes",
"the",
"fd",
"before",
"returning",
"the",
"file",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L85-L100 | train |
saltstack/salt | salt/utils/files.py | recursive_copy | def recursive_copy(source, dest):
'''
Recursively copy the source directory to the destination,
leaving files with the source does not explicitly overwrite.
(identical to cp -r on a unix machine)
'''
for root, _, files in salt.utils.path.os_walk(source):
path_from_source = root.replace(source, '').lstrip(os.sep)
target_directory = os.path.join(dest, path_from_source)
if not os.path.exists(target_directory):
os.makedirs(target_directory)
for name in files:
file_path_from_source = os.path.join(source, path_from_source, name)
target_path = os.path.join(target_directory, name)
shutil.copyfile(file_path_from_source, target_path) | python | def recursive_copy(source, dest):
'''
Recursively copy the source directory to the destination,
leaving files with the source does not explicitly overwrite.
(identical to cp -r on a unix machine)
'''
for root, _, files in salt.utils.path.os_walk(source):
path_from_source = root.replace(source, '').lstrip(os.sep)
target_directory = os.path.join(dest, path_from_source)
if not os.path.exists(target_directory):
os.makedirs(target_directory)
for name in files:
file_path_from_source = os.path.join(source, path_from_source, name)
target_path = os.path.join(target_directory, name)
shutil.copyfile(file_path_from_source, target_path) | [
"def",
"recursive_copy",
"(",
"source",
",",
"dest",
")",
":",
"for",
"root",
",",
"_",
",",
"files",
"in",
"salt",
".",
"utils",
".",
"path",
".",
"os_walk",
"(",
"source",
")",
":",
"path_from_source",
"=",
"root",
".",
"replace",
"(",
"source",
",... | Recursively copy the source directory to the destination,
leaving files with the source does not explicitly overwrite.
(identical to cp -r on a unix machine) | [
"Recursively",
"copy",
"the",
"source",
"directory",
"to",
"the",
"destination",
"leaving",
"files",
"with",
"the",
"source",
"does",
"not",
"explicitly",
"overwrite",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L103-L118 | train |
saltstack/salt | salt/utils/files.py | copyfile | def copyfile(source, dest, backup_mode='', cachedir=''):
'''
Copy files from a source to a destination in an atomic way, and if
specified cache the file.
'''
if not os.path.isfile(source):
raise IOError(
'[Errno 2] No such file or directory: {0}'.format(source)
)
if not os.path.isdir(os.path.dirname(dest)):
raise IOError(
'[Errno 2] No such file or directory: {0}'.format(dest)
)
bname = os.path.basename(dest)
dname = os.path.dirname(os.path.abspath(dest))
tgt = mkstemp(prefix=bname, dir=dname)
shutil.copyfile(source, tgt)
bkroot = ''
if cachedir:
bkroot = os.path.join(cachedir, 'file_backup')
if backup_mode == 'minion' or backup_mode == 'both' and bkroot:
if os.path.exists(dest):
backup_minion(dest, bkroot)
if backup_mode == 'master' or backup_mode == 'both' and bkroot:
# TODO, backup to master
pass
# Get current file stats to they can be replicated after the new file is
# moved to the destination path.
fstat = None
if not salt.utils.platform.is_windows():
try:
fstat = os.stat(dest)
except OSError:
pass
# The move could fail if the dest has xattr protections, so delete the
# temp file in this case
try:
shutil.move(tgt, dest)
except Exception:
__clean_tmp(tgt)
raise
if fstat is not None:
os.chown(dest, fstat.st_uid, fstat.st_gid)
os.chmod(dest, fstat.st_mode)
# If SELINUX is available run a restorecon on the file
rcon = salt.utils.path.which('restorecon')
if rcon:
policy = False
try:
policy = salt.modules.selinux.getenforce()
except (ImportError, CommandExecutionError):
pass
if policy == 'Enforcing':
with fopen(os.devnull, 'w') as dev_null:
cmd = [rcon, dest]
subprocess.call(cmd, stdout=dev_null, stderr=dev_null)
if os.path.isfile(tgt):
# The temp file failed to move
__clean_tmp(tgt) | python | def copyfile(source, dest, backup_mode='', cachedir=''):
'''
Copy files from a source to a destination in an atomic way, and if
specified cache the file.
'''
if not os.path.isfile(source):
raise IOError(
'[Errno 2] No such file or directory: {0}'.format(source)
)
if not os.path.isdir(os.path.dirname(dest)):
raise IOError(
'[Errno 2] No such file or directory: {0}'.format(dest)
)
bname = os.path.basename(dest)
dname = os.path.dirname(os.path.abspath(dest))
tgt = mkstemp(prefix=bname, dir=dname)
shutil.copyfile(source, tgt)
bkroot = ''
if cachedir:
bkroot = os.path.join(cachedir, 'file_backup')
if backup_mode == 'minion' or backup_mode == 'both' and bkroot:
if os.path.exists(dest):
backup_minion(dest, bkroot)
if backup_mode == 'master' or backup_mode == 'both' and bkroot:
# TODO, backup to master
pass
# Get current file stats to they can be replicated after the new file is
# moved to the destination path.
fstat = None
if not salt.utils.platform.is_windows():
try:
fstat = os.stat(dest)
except OSError:
pass
# The move could fail if the dest has xattr protections, so delete the
# temp file in this case
try:
shutil.move(tgt, dest)
except Exception:
__clean_tmp(tgt)
raise
if fstat is not None:
os.chown(dest, fstat.st_uid, fstat.st_gid)
os.chmod(dest, fstat.st_mode)
# If SELINUX is available run a restorecon on the file
rcon = salt.utils.path.which('restorecon')
if rcon:
policy = False
try:
policy = salt.modules.selinux.getenforce()
except (ImportError, CommandExecutionError):
pass
if policy == 'Enforcing':
with fopen(os.devnull, 'w') as dev_null:
cmd = [rcon, dest]
subprocess.call(cmd, stdout=dev_null, stderr=dev_null)
if os.path.isfile(tgt):
# The temp file failed to move
__clean_tmp(tgt) | [
"def",
"copyfile",
"(",
"source",
",",
"dest",
",",
"backup_mode",
"=",
"''",
",",
"cachedir",
"=",
"''",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"source",
")",
":",
"raise",
"IOError",
"(",
"'[Errno 2] No such file or directory: {0}'... | Copy files from a source to a destination in an atomic way, and if
specified cache the file. | [
"Copy",
"files",
"from",
"a",
"source",
"to",
"a",
"destination",
"in",
"an",
"atomic",
"way",
"and",
"if",
"specified",
"cache",
"the",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L121-L181 | train |
saltstack/salt | salt/utils/files.py | rename | def rename(src, dst):
'''
On Windows, os.rename() will fail with a WindowsError exception if a file
exists at the destination path. This function checks for this error and if
found, it deletes the destination path first.
'''
try:
os.rename(src, dst)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
try:
os.remove(dst)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise MinionError(
'Error: Unable to remove {0}: {1}'.format(
dst,
exc.strerror
)
)
os.rename(src, dst) | python | def rename(src, dst):
'''
On Windows, os.rename() will fail with a WindowsError exception if a file
exists at the destination path. This function checks for this error and if
found, it deletes the destination path first.
'''
try:
os.rename(src, dst)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
try:
os.remove(dst)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise MinionError(
'Error: Unable to remove {0}: {1}'.format(
dst,
exc.strerror
)
)
os.rename(src, dst) | [
"def",
"rename",
"(",
"src",
",",
"dst",
")",
":",
"try",
":",
"os",
".",
"rename",
"(",
"src",
",",
"dst",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"try",
":",
"os",
"."... | On Windows, os.rename() will fail with a WindowsError exception if a file
exists at the destination path. This function checks for this error and if
found, it deletes the destination path first. | [
"On",
"Windows",
"os",
".",
"rename",
"()",
"will",
"fail",
"with",
"a",
"WindowsError",
"exception",
"if",
"a",
"file",
"exists",
"at",
"the",
"destination",
"path",
".",
"This",
"function",
"checks",
"for",
"this",
"error",
"and",
"if",
"found",
"it",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L184-L205 | train |
saltstack/salt | salt/utils/files.py | process_read_exception | def process_read_exception(exc, path, ignore=None):
'''
Common code for raising exceptions when reading a file fails
The ignore argument can be an iterable of integer error codes (or a single
integer error code) that should be ignored.
'''
if ignore is not None:
if isinstance(ignore, six.integer_types):
ignore = (ignore,)
else:
ignore = ()
if exc.errno in ignore:
return
if exc.errno == errno.ENOENT:
raise CommandExecutionError('{0} does not exist'.format(path))
elif exc.errno == errno.EACCES:
raise CommandExecutionError(
'Permission denied reading from {0}'.format(path)
)
else:
raise CommandExecutionError(
'Error {0} encountered reading from {1}: {2}'.format(
exc.errno, path, exc.strerror
)
) | python | def process_read_exception(exc, path, ignore=None):
'''
Common code for raising exceptions when reading a file fails
The ignore argument can be an iterable of integer error codes (or a single
integer error code) that should be ignored.
'''
if ignore is not None:
if isinstance(ignore, six.integer_types):
ignore = (ignore,)
else:
ignore = ()
if exc.errno in ignore:
return
if exc.errno == errno.ENOENT:
raise CommandExecutionError('{0} does not exist'.format(path))
elif exc.errno == errno.EACCES:
raise CommandExecutionError(
'Permission denied reading from {0}'.format(path)
)
else:
raise CommandExecutionError(
'Error {0} encountered reading from {1}: {2}'.format(
exc.errno, path, exc.strerror
)
) | [
"def",
"process_read_exception",
"(",
"exc",
",",
"path",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"ignore",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"ignore",
",",
"six",
".",
"integer_types",
")",
":",
"ignore",
"=",
"(",
"ignore",
",",
... | Common code for raising exceptions when reading a file fails
The ignore argument can be an iterable of integer error codes (or a single
integer error code) that should be ignored. | [
"Common",
"code",
"for",
"raising",
"exceptions",
"when",
"reading",
"a",
"file",
"fails"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L208-L235 | train |
saltstack/salt | salt/utils/files.py | wait_lock | def wait_lock(path, lock_fn=None, timeout=5, sleep=0.1, time_start=None):
'''
Obtain a write lock. If one exists, wait for it to release first
'''
if not isinstance(path, six.string_types):
raise FileLockError('path must be a string')
if lock_fn is None:
lock_fn = path + '.w'
if time_start is None:
time_start = time.time()
obtained_lock = False
def _raise_error(msg, race=False):
'''
Raise a FileLockError
'''
raise FileLockError(msg, time_start=time_start)
try:
if os.path.exists(lock_fn) and not os.path.isfile(lock_fn):
_raise_error(
'lock_fn {0} exists and is not a file'.format(lock_fn)
)
open_flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
while time.time() - time_start < timeout:
try:
# Use os.open() to obtain filehandle so that we can force an
# exception if the file already exists. Concept found here:
# http://stackoverflow.com/a/10979569
fh_ = os.open(lock_fn, open_flags)
except (IOError, OSError) as exc:
if exc.errno != errno.EEXIST:
_raise_error(
'Error {0} encountered obtaining file lock {1}: {2}'
.format(exc.errno, lock_fn, exc.strerror)
)
log.trace(
'Lock file %s exists, sleeping %f seconds', lock_fn, sleep
)
time.sleep(sleep)
else:
# Write the lock file
with os.fdopen(fh_, 'w'):
pass
# Lock successfully acquired
log.trace('Write lock %s obtained', lock_fn)
obtained_lock = True
# Transfer control back to the code inside the with block
yield
# Exit the loop
break
else:
_raise_error(
'Timeout of {0} seconds exceeded waiting for lock_fn {1} '
'to be released'.format(timeout, lock_fn)
)
except FileLockError:
raise
except Exception as exc:
_raise_error(
'Error encountered obtaining file lock {0}: {1}'.format(
lock_fn,
exc
)
)
finally:
if obtained_lock:
os.remove(lock_fn)
log.trace('Write lock for %s (%s) released', path, lock_fn) | python | def wait_lock(path, lock_fn=None, timeout=5, sleep=0.1, time_start=None):
'''
Obtain a write lock. If one exists, wait for it to release first
'''
if not isinstance(path, six.string_types):
raise FileLockError('path must be a string')
if lock_fn is None:
lock_fn = path + '.w'
if time_start is None:
time_start = time.time()
obtained_lock = False
def _raise_error(msg, race=False):
'''
Raise a FileLockError
'''
raise FileLockError(msg, time_start=time_start)
try:
if os.path.exists(lock_fn) and not os.path.isfile(lock_fn):
_raise_error(
'lock_fn {0} exists and is not a file'.format(lock_fn)
)
open_flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
while time.time() - time_start < timeout:
try:
# Use os.open() to obtain filehandle so that we can force an
# exception if the file already exists. Concept found here:
# http://stackoverflow.com/a/10979569
fh_ = os.open(lock_fn, open_flags)
except (IOError, OSError) as exc:
if exc.errno != errno.EEXIST:
_raise_error(
'Error {0} encountered obtaining file lock {1}: {2}'
.format(exc.errno, lock_fn, exc.strerror)
)
log.trace(
'Lock file %s exists, sleeping %f seconds', lock_fn, sleep
)
time.sleep(sleep)
else:
# Write the lock file
with os.fdopen(fh_, 'w'):
pass
# Lock successfully acquired
log.trace('Write lock %s obtained', lock_fn)
obtained_lock = True
# Transfer control back to the code inside the with block
yield
# Exit the loop
break
else:
_raise_error(
'Timeout of {0} seconds exceeded waiting for lock_fn {1} '
'to be released'.format(timeout, lock_fn)
)
except FileLockError:
raise
except Exception as exc:
_raise_error(
'Error encountered obtaining file lock {0}: {1}'.format(
lock_fn,
exc
)
)
finally:
if obtained_lock:
os.remove(lock_fn)
log.trace('Write lock for %s (%s) released', path, lock_fn) | [
"def",
"wait_lock",
"(",
"path",
",",
"lock_fn",
"=",
"None",
",",
"timeout",
"=",
"5",
",",
"sleep",
"=",
"0.1",
",",
"time_start",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"string_types",
")",
":",
"raise",
... | Obtain a write lock. If one exists, wait for it to release first | [
"Obtain",
"a",
"write",
"lock",
".",
"If",
"one",
"exists",
"wait",
"for",
"it",
"to",
"release",
"first"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L239-L312 | train |
saltstack/salt | salt/utils/files.py | set_umask | def set_umask(mask):
'''
Temporarily set the umask and restore once the contextmanager exits
'''
if mask is None or salt.utils.platform.is_windows():
# Don't attempt on Windows, or if no mask was passed
yield
else:
try:
orig_mask = os.umask(mask) # pylint: disable=blacklisted-function
yield
finally:
os.umask(orig_mask) | python | def set_umask(mask):
'''
Temporarily set the umask and restore once the contextmanager exits
'''
if mask is None or salt.utils.platform.is_windows():
# Don't attempt on Windows, or if no mask was passed
yield
else:
try:
orig_mask = os.umask(mask) # pylint: disable=blacklisted-function
yield
finally:
os.umask(orig_mask) | [
"def",
"set_umask",
"(",
"mask",
")",
":",
"if",
"mask",
"is",
"None",
"or",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"# Don't attempt on Windows, or if no mask was passed",
"yield",
"else",
":",
"try",
":",
"orig_mask",
"=",
... | Temporarily set the umask and restore once the contextmanager exits | [
"Temporarily",
"set",
"the",
"umask",
"and",
"restore",
"once",
"the",
"contextmanager",
"exits"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L325-L337 | train |
saltstack/salt | salt/utils/files.py | fopen | def fopen(*args, **kwargs):
'''
Wrapper around open() built-in to set CLOEXEC on the fd.
This flag specifies that the file descriptor should be closed when an exec
function is invoked;
When a file descriptor is allocated (as with open or dup), this bit is
initially cleared on the new file descriptor, meaning that descriptor will
survive into the new program after exec.
NB! We still have small race condition between open and fcntl.
'''
if six.PY3:
try:
# Don't permit stdin/stdout/stderr to be opened. The boolean False
# and True are treated by Python 3's open() as file descriptors 0
# and 1, respectively.
if args[0] in (0, 1, 2):
raise TypeError(
'{0} is not a permitted file descriptor'.format(args[0])
)
except IndexError:
pass
binary = None
# ensure 'binary' mode is always used on Windows in Python 2
if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or
kwargs.pop('binary', False)):
if len(args) > 1:
args = list(args)
if 'b' not in args[1]:
args[1] = args[1].replace('t', 'b')
if 'b' not in args[1]:
args[1] += 'b'
elif kwargs.get('mode'):
if 'b' not in kwargs['mode']:
kwargs['mode'] = kwargs['mode'].replace('t', 'b')
if 'b' not in kwargs['mode']:
kwargs['mode'] += 'b'
else:
# the default is to read
kwargs['mode'] = 'rb'
elif six.PY3 and 'encoding' not in kwargs:
# In Python 3, if text mode is used and the encoding
# is not specified, set the encoding to 'utf-8'.
binary = False
if len(args) > 1:
args = list(args)
if 'b' in args[1]:
binary = True
if kwargs.get('mode', None):
if 'b' in kwargs['mode']:
binary = True
if not binary:
kwargs['encoding'] = __salt_system_encoding__
if six.PY3 and not binary and not kwargs.get('newline', None):
kwargs['newline'] = ''
f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage
if is_fcntl_available():
# modify the file descriptor on systems with fcntl
# unix and unix-like systems only
try:
FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103
except AttributeError:
FD_CLOEXEC = 1 # pylint: disable=C0103
old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)
fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)
return f_handle | python | def fopen(*args, **kwargs):
'''
Wrapper around open() built-in to set CLOEXEC on the fd.
This flag specifies that the file descriptor should be closed when an exec
function is invoked;
When a file descriptor is allocated (as with open or dup), this bit is
initially cleared on the new file descriptor, meaning that descriptor will
survive into the new program after exec.
NB! We still have small race condition between open and fcntl.
'''
if six.PY3:
try:
# Don't permit stdin/stdout/stderr to be opened. The boolean False
# and True are treated by Python 3's open() as file descriptors 0
# and 1, respectively.
if args[0] in (0, 1, 2):
raise TypeError(
'{0} is not a permitted file descriptor'.format(args[0])
)
except IndexError:
pass
binary = None
# ensure 'binary' mode is always used on Windows in Python 2
if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or
kwargs.pop('binary', False)):
if len(args) > 1:
args = list(args)
if 'b' not in args[1]:
args[1] = args[1].replace('t', 'b')
if 'b' not in args[1]:
args[1] += 'b'
elif kwargs.get('mode'):
if 'b' not in kwargs['mode']:
kwargs['mode'] = kwargs['mode'].replace('t', 'b')
if 'b' not in kwargs['mode']:
kwargs['mode'] += 'b'
else:
# the default is to read
kwargs['mode'] = 'rb'
elif six.PY3 and 'encoding' not in kwargs:
# In Python 3, if text mode is used and the encoding
# is not specified, set the encoding to 'utf-8'.
binary = False
if len(args) > 1:
args = list(args)
if 'b' in args[1]:
binary = True
if kwargs.get('mode', None):
if 'b' in kwargs['mode']:
binary = True
if not binary:
kwargs['encoding'] = __salt_system_encoding__
if six.PY3 and not binary and not kwargs.get('newline', None):
kwargs['newline'] = ''
f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage
if is_fcntl_available():
# modify the file descriptor on systems with fcntl
# unix and unix-like systems only
try:
FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103
except AttributeError:
FD_CLOEXEC = 1 # pylint: disable=C0103
old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)
fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)
return f_handle | [
"def",
"fopen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY3",
":",
"try",
":",
"# Don't permit stdin/stdout/stderr to be opened. The boolean False",
"# and True are treated by Python 3's open() as file descriptors 0",
"# and 1, respectively.",
... | Wrapper around open() built-in to set CLOEXEC on the fd.
This flag specifies that the file descriptor should be closed when an exec
function is invoked;
When a file descriptor is allocated (as with open or dup), this bit is
initially cleared on the new file descriptor, meaning that descriptor will
survive into the new program after exec.
NB! We still have small race condition between open and fcntl. | [
"Wrapper",
"around",
"open",
"()",
"built",
"-",
"in",
"to",
"set",
"CLOEXEC",
"on",
"the",
"fd",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L340-L411 | train |
saltstack/salt | salt/utils/files.py | flopen | def flopen(*args, **kwargs):
'''
Shortcut for fopen with lock and context manager.
'''
filename, args = args[0], args[1:]
writing = 'wa'
with fopen(filename, *args, **kwargs) as f_handle:
try:
if is_fcntl_available(check_sunos=True):
lock_type = fcntl.LOCK_SH
if args and any([write in args[0] for write in writing]):
lock_type = fcntl.LOCK_EX
fcntl.flock(f_handle.fileno(), lock_type)
yield f_handle
finally:
if is_fcntl_available(check_sunos=True):
fcntl.flock(f_handle.fileno(), fcntl.LOCK_UN) | python | def flopen(*args, **kwargs):
'''
Shortcut for fopen with lock and context manager.
'''
filename, args = args[0], args[1:]
writing = 'wa'
with fopen(filename, *args, **kwargs) as f_handle:
try:
if is_fcntl_available(check_sunos=True):
lock_type = fcntl.LOCK_SH
if args and any([write in args[0] for write in writing]):
lock_type = fcntl.LOCK_EX
fcntl.flock(f_handle.fileno(), lock_type)
yield f_handle
finally:
if is_fcntl_available(check_sunos=True):
fcntl.flock(f_handle.fileno(), fcntl.LOCK_UN) | [
"def",
"flopen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"filename",
",",
"args",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
":",
"]",
"writing",
"=",
"'wa'",
"with",
"fopen",
"(",
"filename",
",",
"*",
"args",
",",
"*",
... | Shortcut for fopen with lock and context manager. | [
"Shortcut",
"for",
"fopen",
"with",
"lock",
"and",
"context",
"manager",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L415-L431 | train |
saltstack/salt | salt/utils/files.py | fpopen | def fpopen(*args, **kwargs):
'''
Shortcut for fopen with extra uid, gid, and mode options.
Supported optional Keyword Arguments:
mode
Explicit mode to set. Mode is anything os.chmod would accept
as input for mode. Works only on unix/unix-like systems.
uid
The uid to set, if not set, or it is None or -1 no changes are
made. Same applies if the path is already owned by this uid.
Must be int. Works only on unix/unix-like systems.
gid
The gid to set, if not set, or it is None or -1 no changes are
made. Same applies if the path is already owned by this gid.
Must be int. Works only on unix/unix-like systems.
'''
# Remove uid, gid and mode from kwargs if present
uid = kwargs.pop('uid', -1) # -1 means no change to current uid
gid = kwargs.pop('gid', -1) # -1 means no change to current gid
mode = kwargs.pop('mode', None)
with fopen(*args, **kwargs) as f_handle:
path = args[0]
d_stat = os.stat(path)
if hasattr(os, 'chown'):
# if uid and gid are both -1 then go ahead with
# no changes at all
if (d_stat.st_uid != uid or d_stat.st_gid != gid) and \
[i for i in (uid, gid) if i != -1]:
os.chown(path, uid, gid)
if mode is not None:
mode_part = stat.S_IMODE(d_stat.st_mode)
if mode_part != mode:
os.chmod(path, (d_stat.st_mode ^ mode_part) | mode)
yield f_handle | python | def fpopen(*args, **kwargs):
'''
Shortcut for fopen with extra uid, gid, and mode options.
Supported optional Keyword Arguments:
mode
Explicit mode to set. Mode is anything os.chmod would accept
as input for mode. Works only on unix/unix-like systems.
uid
The uid to set, if not set, or it is None or -1 no changes are
made. Same applies if the path is already owned by this uid.
Must be int. Works only on unix/unix-like systems.
gid
The gid to set, if not set, or it is None or -1 no changes are
made. Same applies if the path is already owned by this gid.
Must be int. Works only on unix/unix-like systems.
'''
# Remove uid, gid and mode from kwargs if present
uid = kwargs.pop('uid', -1) # -1 means no change to current uid
gid = kwargs.pop('gid', -1) # -1 means no change to current gid
mode = kwargs.pop('mode', None)
with fopen(*args, **kwargs) as f_handle:
path = args[0]
d_stat = os.stat(path)
if hasattr(os, 'chown'):
# if uid and gid are both -1 then go ahead with
# no changes at all
if (d_stat.st_uid != uid or d_stat.st_gid != gid) and \
[i for i in (uid, gid) if i != -1]:
os.chown(path, uid, gid)
if mode is not None:
mode_part = stat.S_IMODE(d_stat.st_mode)
if mode_part != mode:
os.chmod(path, (d_stat.st_mode ^ mode_part) | mode)
yield f_handle | [
"def",
"fpopen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Remove uid, gid and mode from kwargs if present",
"uid",
"=",
"kwargs",
".",
"pop",
"(",
"'uid'",
",",
"-",
"1",
")",
"# -1 means no change to current uid",
"gid",
"=",
"kwargs",
".",
"po... | Shortcut for fopen with extra uid, gid, and mode options.
Supported optional Keyword Arguments:
mode
Explicit mode to set. Mode is anything os.chmod would accept
as input for mode. Works only on unix/unix-like systems.
uid
The uid to set, if not set, or it is None or -1 no changes are
made. Same applies if the path is already owned by this uid.
Must be int. Works only on unix/unix-like systems.
gid
The gid to set, if not set, or it is None or -1 no changes are
made. Same applies if the path is already owned by this gid.
Must be int. Works only on unix/unix-like systems. | [
"Shortcut",
"for",
"fopen",
"with",
"extra",
"uid",
"gid",
"and",
"mode",
"options",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L435-L476 | train |
saltstack/salt | salt/utils/files.py | safe_walk | def safe_walk(top, topdown=True, onerror=None, followlinks=True, _seen=None):
'''
A clone of the python os.walk function with some checks for recursive
symlinks. Unlike os.walk this follows symlinks by default.
'''
if _seen is None:
_seen = set()
# We may not have read permission for top, in which case we can't
# get a list of the files the directory contains. os.path.walk
# always suppressed the exception then, rather than blow up for a
# minor reason when (say) a thousand readable directories are still
# left to visit. That logic is copied here.
try:
# Note that listdir and error are globals in this module due
# to earlier import-*.
names = os.listdir(top)
except os.error as err:
if onerror is not None:
onerror(err)
return
if followlinks:
status = os.stat(top)
# st_ino is always 0 on some filesystems (FAT, NTFS); ignore them
if status.st_ino != 0:
node = (status.st_dev, status.st_ino)
if node in _seen:
return
_seen.add(node)
dirs, nondirs = [], []
for name in names:
full_path = os.path.join(top, name)
if os.path.isdir(full_path):
dirs.append(name)
else:
nondirs.append(name)
if topdown:
yield top, dirs, nondirs
for name in dirs:
new_path = os.path.join(top, name)
if followlinks or not os.path.islink(new_path):
for x in safe_walk(new_path, topdown, onerror, followlinks, _seen):
yield x
if not topdown:
yield top, dirs, nondirs | python | def safe_walk(top, topdown=True, onerror=None, followlinks=True, _seen=None):
'''
A clone of the python os.walk function with some checks for recursive
symlinks. Unlike os.walk this follows symlinks by default.
'''
if _seen is None:
_seen = set()
# We may not have read permission for top, in which case we can't
# get a list of the files the directory contains. os.path.walk
# always suppressed the exception then, rather than blow up for a
# minor reason when (say) a thousand readable directories are still
# left to visit. That logic is copied here.
try:
# Note that listdir and error are globals in this module due
# to earlier import-*.
names = os.listdir(top)
except os.error as err:
if onerror is not None:
onerror(err)
return
if followlinks:
status = os.stat(top)
# st_ino is always 0 on some filesystems (FAT, NTFS); ignore them
if status.st_ino != 0:
node = (status.st_dev, status.st_ino)
if node in _seen:
return
_seen.add(node)
dirs, nondirs = [], []
for name in names:
full_path = os.path.join(top, name)
if os.path.isdir(full_path):
dirs.append(name)
else:
nondirs.append(name)
if topdown:
yield top, dirs, nondirs
for name in dirs:
new_path = os.path.join(top, name)
if followlinks or not os.path.islink(new_path):
for x in safe_walk(new_path, topdown, onerror, followlinks, _seen):
yield x
if not topdown:
yield top, dirs, nondirs | [
"def",
"safe_walk",
"(",
"top",
",",
"topdown",
"=",
"True",
",",
"onerror",
"=",
"None",
",",
"followlinks",
"=",
"True",
",",
"_seen",
"=",
"None",
")",
":",
"if",
"_seen",
"is",
"None",
":",
"_seen",
"=",
"set",
"(",
")",
"# We may not have read per... | A clone of the python os.walk function with some checks for recursive
symlinks. Unlike os.walk this follows symlinks by default. | [
"A",
"clone",
"of",
"the",
"python",
"os",
".",
"walk",
"function",
"with",
"some",
"checks",
"for",
"recursive",
"symlinks",
".",
"Unlike",
"os",
".",
"walk",
"this",
"follows",
"symlinks",
"by",
"default",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L479-L526 | train |
saltstack/salt | salt/utils/files.py | rm_rf | def rm_rf(path):
'''
Platform-independent recursive delete. Includes code from
http://stackoverflow.com/a/2656405
'''
def _onerror(func, path, exc_info):
'''
Error handler for `shutil.rmtree`.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : `shutil.rmtree(path, onerror=onerror)`
'''
if salt.utils.platform.is_windows() and not os.access(path, os.W_OK):
# Is the error an access error ?
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise # pylint: disable=E0704
if os.path.islink(path) or not os.path.isdir(path):
os.remove(path)
else:
if salt.utils.platform.is_windows():
try:
path = salt.utils.stringutils.to_unicode(path)
except TypeError:
pass
shutil.rmtree(path, onerror=_onerror) | python | def rm_rf(path):
'''
Platform-independent recursive delete. Includes code from
http://stackoverflow.com/a/2656405
'''
def _onerror(func, path, exc_info):
'''
Error handler for `shutil.rmtree`.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : `shutil.rmtree(path, onerror=onerror)`
'''
if salt.utils.platform.is_windows() and not os.access(path, os.W_OK):
# Is the error an access error ?
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise # pylint: disable=E0704
if os.path.islink(path) or not os.path.isdir(path):
os.remove(path)
else:
if salt.utils.platform.is_windows():
try:
path = salt.utils.stringutils.to_unicode(path)
except TypeError:
pass
shutil.rmtree(path, onerror=_onerror) | [
"def",
"rm_rf",
"(",
"path",
")",
":",
"def",
"_onerror",
"(",
"func",
",",
"path",
",",
"exc_info",
")",
":",
"'''\n Error handler for `shutil.rmtree`.\n\n If the error is due to an access error (read only file)\n it attempts to add write permission and then ret... | Platform-independent recursive delete. Includes code from
http://stackoverflow.com/a/2656405 | [
"Platform",
"-",
"independent",
"recursive",
"delete",
".",
"Includes",
"code",
"from",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"2656405"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L539-L569 | train |
saltstack/salt | salt/utils/files.py | is_fcntl_available | def is_fcntl_available(check_sunos=False):
'''
Simple function to check if the ``fcntl`` module is available or not.
If ``check_sunos`` is passed as ``True`` an additional check to see if host is
SunOS is also made. For additional information see: http://goo.gl/159FF8
'''
if check_sunos and salt.utils.platform.is_sunos():
return False
return HAS_FCNTL | python | def is_fcntl_available(check_sunos=False):
'''
Simple function to check if the ``fcntl`` module is available or not.
If ``check_sunos`` is passed as ``True`` an additional check to see if host is
SunOS is also made. For additional information see: http://goo.gl/159FF8
'''
if check_sunos and salt.utils.platform.is_sunos():
return False
return HAS_FCNTL | [
"def",
"is_fcntl_available",
"(",
"check_sunos",
"=",
"False",
")",
":",
"if",
"check_sunos",
"and",
"salt",
".",
"utils",
".",
"platform",
".",
"is_sunos",
"(",
")",
":",
"return",
"False",
"return",
"HAS_FCNTL"
] | Simple function to check if the ``fcntl`` module is available or not.
If ``check_sunos`` is passed as ``True`` an additional check to see if host is
SunOS is also made. For additional information see: http://goo.gl/159FF8 | [
"Simple",
"function",
"to",
"check",
"if",
"the",
"fcntl",
"module",
"is",
"available",
"or",
"not",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L584-L593 | train |
saltstack/salt | salt/utils/files.py | safe_filename_leaf | def safe_filename_leaf(file_basename):
'''
Input the basename of a file, without the directory tree, and returns a safe name to use
i.e. only the required characters are converted by urllib.quote
If the input is a PY2 String, output a PY2 String. If input is Unicode output Unicode.
For consistency all platforms are treated the same. Hard coded to utf8 as its ascii compatible
windows is \\ / : * ? " < > | posix is /
.. versionadded:: 2017.7.2
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
def _replace(re_obj):
return quote(re_obj.group(0), safe='')
if not isinstance(file_basename, six.text_type):
# the following string is not prefixed with u
return re.sub('[\\\\:/*?"<>|]',
_replace,
six.text_type(file_basename, 'utf8').encode('ascii', 'backslashreplace'))
# the following string is prefixed with u
return re.sub('[\\\\:/*?"<>|]', _replace, file_basename, flags=re.UNICODE) | python | def safe_filename_leaf(file_basename):
'''
Input the basename of a file, without the directory tree, and returns a safe name to use
i.e. only the required characters are converted by urllib.quote
If the input is a PY2 String, output a PY2 String. If input is Unicode output Unicode.
For consistency all platforms are treated the same. Hard coded to utf8 as its ascii compatible
windows is \\ / : * ? " < > | posix is /
.. versionadded:: 2017.7.2
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
def _replace(re_obj):
return quote(re_obj.group(0), safe='')
if not isinstance(file_basename, six.text_type):
# the following string is not prefixed with u
return re.sub('[\\\\:/*?"<>|]',
_replace,
six.text_type(file_basename, 'utf8').encode('ascii', 'backslashreplace'))
# the following string is prefixed with u
return re.sub('[\\\\:/*?"<>|]', _replace, file_basename, flags=re.UNICODE) | [
"def",
"safe_filename_leaf",
"(",
"file_basename",
")",
":",
"def",
"_replace",
"(",
"re_obj",
")",
":",
"return",
"quote",
"(",
"re_obj",
".",
"group",
"(",
"0",
")",
",",
"safe",
"=",
"''",
")",
"if",
"not",
"isinstance",
"(",
"file_basename",
",",
"... | Input the basename of a file, without the directory tree, and returns a safe name to use
i.e. only the required characters are converted by urllib.quote
If the input is a PY2 String, output a PY2 String. If input is Unicode output Unicode.
For consistency all platforms are treated the same. Hard coded to utf8 as its ascii compatible
windows is \\ / : * ? " < > | posix is /
.. versionadded:: 2017.7.2
:codeauthor: Damon Atkins <https://github.com/damon-atkins> | [
"Input",
"the",
"basename",
"of",
"a",
"file",
"without",
"the",
"directory",
"tree",
"and",
"returns",
"a",
"safe",
"name",
"to",
"use",
"i",
".",
"e",
".",
"only",
"the",
"required",
"characters",
"are",
"converted",
"by",
"urllib",
".",
"quote",
"If",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L596-L616 | train |
saltstack/salt | salt/utils/files.py | safe_filepath | def safe_filepath(file_path_name, dir_sep=None):
'''
Input the full path and filename, splits on directory separator and calls safe_filename_leaf for
each part of the path. dir_sep allows coder to force a directory separate to a particular character
.. versionadded:: 2017.7.2
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
if not dir_sep:
dir_sep = os.sep
# Normally if file_path_name or dir_sep is Unicode then the output will be Unicode
# This code ensure the output type is the same as file_path_name
if not isinstance(file_path_name, six.text_type) and isinstance(dir_sep, six.text_type):
dir_sep = dir_sep.encode('ascii') # This should not be executed under PY3
# splitdrive only set drive on windows platform
(drive, path) = os.path.splitdrive(file_path_name)
path = dir_sep.join([safe_filename_leaf(file_section) for file_section in path.rsplit(dir_sep)])
if drive:
path = dir_sep.join([drive, path])
return path | python | def safe_filepath(file_path_name, dir_sep=None):
'''
Input the full path and filename, splits on directory separator and calls safe_filename_leaf for
each part of the path. dir_sep allows coder to force a directory separate to a particular character
.. versionadded:: 2017.7.2
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
'''
if not dir_sep:
dir_sep = os.sep
# Normally if file_path_name or dir_sep is Unicode then the output will be Unicode
# This code ensure the output type is the same as file_path_name
if not isinstance(file_path_name, six.text_type) and isinstance(dir_sep, six.text_type):
dir_sep = dir_sep.encode('ascii') # This should not be executed under PY3
# splitdrive only set drive on windows platform
(drive, path) = os.path.splitdrive(file_path_name)
path = dir_sep.join([safe_filename_leaf(file_section) for file_section in path.rsplit(dir_sep)])
if drive:
path = dir_sep.join([drive, path])
return path | [
"def",
"safe_filepath",
"(",
"file_path_name",
",",
"dir_sep",
"=",
"None",
")",
":",
"if",
"not",
"dir_sep",
":",
"dir_sep",
"=",
"os",
".",
"sep",
"# Normally if file_path_name or dir_sep is Unicode then the output will be Unicode",
"# This code ensure the output type is th... | Input the full path and filename, splits on directory separator and calls safe_filename_leaf for
each part of the path. dir_sep allows coder to force a directory separate to a particular character
.. versionadded:: 2017.7.2
:codeauthor: Damon Atkins <https://github.com/damon-atkins> | [
"Input",
"the",
"full",
"path",
"and",
"filename",
"splits",
"on",
"directory",
"separator",
"and",
"calls",
"safe_filename_leaf",
"for",
"each",
"part",
"of",
"the",
"path",
".",
"dir_sep",
"allows",
"coder",
"to",
"force",
"a",
"directory",
"separate",
"to",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L619-L639 | train |
saltstack/salt | salt/utils/files.py | is_text | def is_text(fp_, blocksize=512):
'''
Uses heuristics to guess whether the given file is text or binary,
by reading a single block of bytes from the file.
If more than 30% of the chars in the block are non-text, or there
are NUL ('\x00') bytes in the block, assume this is a binary file.
'''
int2byte = (lambda x: bytes((x,))) if six.PY3 else chr
text_characters = (
b''.join(int2byte(i) for i in range(32, 127)) +
b'\n\r\t\f\b')
try:
block = fp_.read(blocksize)
except AttributeError:
# This wasn't an open filehandle, so treat it as a file path and try to
# open the file
try:
with fopen(fp_, 'rb') as fp2_:
block = fp2_.read(blocksize)
except IOError:
# Unable to open file, bail out and return false
return False
if b'\x00' in block:
# Files with null bytes are binary
return False
elif not block:
# An empty file is considered a valid text file
return True
try:
block.decode('utf-8')
return True
except UnicodeDecodeError:
pass
nontext = block.translate(None, text_characters)
return float(len(nontext)) / len(block) <= 0.30 | python | def is_text(fp_, blocksize=512):
'''
Uses heuristics to guess whether the given file is text or binary,
by reading a single block of bytes from the file.
If more than 30% of the chars in the block are non-text, or there
are NUL ('\x00') bytes in the block, assume this is a binary file.
'''
int2byte = (lambda x: bytes((x,))) if six.PY3 else chr
text_characters = (
b''.join(int2byte(i) for i in range(32, 127)) +
b'\n\r\t\f\b')
try:
block = fp_.read(blocksize)
except AttributeError:
# This wasn't an open filehandle, so treat it as a file path and try to
# open the file
try:
with fopen(fp_, 'rb') as fp2_:
block = fp2_.read(blocksize)
except IOError:
# Unable to open file, bail out and return false
return False
if b'\x00' in block:
# Files with null bytes are binary
return False
elif not block:
# An empty file is considered a valid text file
return True
try:
block.decode('utf-8')
return True
except UnicodeDecodeError:
pass
nontext = block.translate(None, text_characters)
return float(len(nontext)) / len(block) <= 0.30 | [
"def",
"is_text",
"(",
"fp_",
",",
"blocksize",
"=",
"512",
")",
":",
"int2byte",
"=",
"(",
"lambda",
"x",
":",
"bytes",
"(",
"(",
"x",
",",
")",
")",
")",
"if",
"six",
".",
"PY3",
"else",
"chr",
"text_characters",
"=",
"(",
"b''",
".",
"join",
... | Uses heuristics to guess whether the given file is text or binary,
by reading a single block of bytes from the file.
If more than 30% of the chars in the block are non-text, or there
are NUL ('\x00') bytes in the block, assume this is a binary file. | [
"Uses",
"heuristics",
"to",
"guess",
"whether",
"the",
"given",
"file",
"is",
"text",
"or",
"binary",
"by",
"reading",
"a",
"single",
"block",
"of",
"bytes",
"from",
"the",
"file",
".",
"If",
"more",
"than",
"30%",
"of",
"the",
"chars",
"in",
"the",
"b... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L643-L678 | train |
saltstack/salt | salt/utils/files.py | is_binary | def is_binary(path):
'''
Detects if the file is a binary, returns bool. Returns True if the file is
a bin, False if the file is not and None if the file is not available.
'''
if not os.path.isfile(path):
return False
try:
with fopen(path, 'rb') as fp_:
try:
data = fp_.read(2048)
if six.PY3:
data = data.decode(__salt_system_encoding__)
return salt.utils.stringutils.is_binary(data)
except UnicodeDecodeError:
return True
except os.error:
return False | python | def is_binary(path):
'''
Detects if the file is a binary, returns bool. Returns True if the file is
a bin, False if the file is not and None if the file is not available.
'''
if not os.path.isfile(path):
return False
try:
with fopen(path, 'rb') as fp_:
try:
data = fp_.read(2048)
if six.PY3:
data = data.decode(__salt_system_encoding__)
return salt.utils.stringutils.is_binary(data)
except UnicodeDecodeError:
return True
except os.error:
return False | [
"def",
"is_binary",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"False",
"try",
":",
"with",
"fopen",
"(",
"path",
",",
"'rb'",
")",
"as",
"fp_",
":",
"try",
":",
"data",
"=",
"fp_",
".... | Detects if the file is a binary, returns bool. Returns True if the file is
a bin, False if the file is not and None if the file is not available. | [
"Detects",
"if",
"the",
"file",
"is",
"a",
"binary",
"returns",
"bool",
".",
"Returns",
"True",
"if",
"the",
"file",
"is",
"a",
"bin",
"False",
"if",
"the",
"file",
"is",
"not",
"and",
"None",
"if",
"the",
"file",
"is",
"not",
"available",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L682-L699 | train |
saltstack/salt | salt/utils/files.py | remove | def remove(path):
'''
Runs os.remove(path) and suppresses the OSError if the file doesn't exist
'''
try:
os.remove(path)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise | python | def remove(path):
'''
Runs os.remove(path) and suppresses the OSError if the file doesn't exist
'''
try:
os.remove(path)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise | [
"def",
"remove",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"path",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise"
] | Runs os.remove(path) and suppresses the OSError if the file doesn't exist | [
"Runs",
"os",
".",
"remove",
"(",
"path",
")",
"and",
"suppresses",
"the",
"OSError",
"if",
"the",
"file",
"doesn",
"t",
"exist"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L702-L710 | train |
saltstack/salt | salt/utils/files.py | list_files | def list_files(directory):
'''
Return a list of all files found under directory (and its subdirectories)
'''
ret = set()
ret.add(directory)
for root, dirs, files in safe_walk(directory):
for name in files:
ret.add(os.path.join(root, name))
for name in dirs:
ret.add(os.path.join(root, name))
return list(ret) | python | def list_files(directory):
'''
Return a list of all files found under directory (and its subdirectories)
'''
ret = set()
ret.add(directory)
for root, dirs, files in safe_walk(directory):
for name in files:
ret.add(os.path.join(root, name))
for name in dirs:
ret.add(os.path.join(root, name))
return list(ret) | [
"def",
"list_files",
"(",
"directory",
")",
":",
"ret",
"=",
"set",
"(",
")",
"ret",
".",
"add",
"(",
"directory",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"safe_walk",
"(",
"directory",
")",
":",
"for",
"name",
"in",
"files",
":",
"ret... | Return a list of all files found under directory (and its subdirectories) | [
"Return",
"a",
"list",
"of",
"all",
"files",
"found",
"under",
"directory",
"(",
"and",
"its",
"subdirectories",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L714-L726 | train |
saltstack/salt | salt/utils/files.py | normalize_mode | def normalize_mode(mode):
'''
Return a mode value, normalized to a string and containing a leading zero
if it does not have one.
Allow "keep" as a valid mode (used by file state/module to preserve mode
from the Salt fileserver in file states).
'''
if mode is None:
return None
if not isinstance(mode, six.string_types):
mode = six.text_type(mode)
if six.PY3:
mode = mode.replace('0o', '0')
# Strip any quotes any initial zeroes, then though zero-pad it up to 4.
# This ensures that somethign like '00644' is normalized to '0644'
return mode.strip('"').strip('\'').lstrip('0').zfill(4) | python | def normalize_mode(mode):
'''
Return a mode value, normalized to a string and containing a leading zero
if it does not have one.
Allow "keep" as a valid mode (used by file state/module to preserve mode
from the Salt fileserver in file states).
'''
if mode is None:
return None
if not isinstance(mode, six.string_types):
mode = six.text_type(mode)
if six.PY3:
mode = mode.replace('0o', '0')
# Strip any quotes any initial zeroes, then though zero-pad it up to 4.
# This ensures that somethign like '00644' is normalized to '0644'
return mode.strip('"').strip('\'').lstrip('0').zfill(4) | [
"def",
"normalize_mode",
"(",
"mode",
")",
":",
"if",
"mode",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"mode",
",",
"six",
".",
"string_types",
")",
":",
"mode",
"=",
"six",
".",
"text_type",
"(",
"mode",
")",
"if",
"six",... | Return a mode value, normalized to a string and containing a leading zero
if it does not have one.
Allow "keep" as a valid mode (used by file state/module to preserve mode
from the Salt fileserver in file states). | [
"Return",
"a",
"mode",
"value",
"normalized",
"to",
"a",
"string",
"and",
"containing",
"a",
"leading",
"zero",
"if",
"it",
"does",
"not",
"have",
"one",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L740-L756 | train |
saltstack/salt | salt/utils/files.py | human_size_to_bytes | def human_size_to_bytes(human_size):
'''
Convert human-readable units to bytes
'''
size_exp_map = {'K': 1, 'M': 2, 'G': 3, 'T': 4, 'P': 5}
human_size_str = six.text_type(human_size)
match = re.match(r'^(\d+)([KMGTP])?$', human_size_str)
if not match:
raise ValueError(
'Size must be all digits, with an optional unit type '
'(K, M, G, T, or P)'
)
size_num = int(match.group(1))
unit_multiplier = 1024 ** size_exp_map.get(match.group(2), 0)
return size_num * unit_multiplier | python | def human_size_to_bytes(human_size):
'''
Convert human-readable units to bytes
'''
size_exp_map = {'K': 1, 'M': 2, 'G': 3, 'T': 4, 'P': 5}
human_size_str = six.text_type(human_size)
match = re.match(r'^(\d+)([KMGTP])?$', human_size_str)
if not match:
raise ValueError(
'Size must be all digits, with an optional unit type '
'(K, M, G, T, or P)'
)
size_num = int(match.group(1))
unit_multiplier = 1024 ** size_exp_map.get(match.group(2), 0)
return size_num * unit_multiplier | [
"def",
"human_size_to_bytes",
"(",
"human_size",
")",
":",
"size_exp_map",
"=",
"{",
"'K'",
":",
"1",
",",
"'M'",
":",
"2",
",",
"'G'",
":",
"3",
",",
"'T'",
":",
"4",
",",
"'P'",
":",
"5",
"}",
"human_size_str",
"=",
"six",
".",
"text_type",
"(",
... | Convert human-readable units to bytes | [
"Convert",
"human",
"-",
"readable",
"units",
"to",
"bytes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L759-L773 | train |
saltstack/salt | salt/utils/files.py | backup_minion | def backup_minion(path, bkroot):
'''
Backup a file on the minion
'''
dname, bname = os.path.split(path)
if salt.utils.platform.is_windows():
src_dir = dname.replace(':', '_')
else:
src_dir = dname[1:]
if not salt.utils.platform.is_windows():
fstat = os.stat(path)
msecs = six.text_type(int(time.time() * 1000000))[-6:]
if salt.utils.platform.is_windows():
# ':' is an illegal filesystem path character on Windows
stamp = time.strftime('%a_%b_%d_%H-%M-%S_%Y')
else:
stamp = time.strftime('%a_%b_%d_%H:%M:%S_%Y')
stamp = '{0}{1}_{2}'.format(stamp[:-4], msecs, stamp[-4:])
bkpath = os.path.join(bkroot,
src_dir,
'{0}_{1}'.format(bname, stamp))
if not os.path.isdir(os.path.dirname(bkpath)):
os.makedirs(os.path.dirname(bkpath))
shutil.copyfile(path, bkpath)
if not salt.utils.platform.is_windows():
os.chown(bkpath, fstat.st_uid, fstat.st_gid)
os.chmod(bkpath, fstat.st_mode) | python | def backup_minion(path, bkroot):
'''
Backup a file on the minion
'''
dname, bname = os.path.split(path)
if salt.utils.platform.is_windows():
src_dir = dname.replace(':', '_')
else:
src_dir = dname[1:]
if not salt.utils.platform.is_windows():
fstat = os.stat(path)
msecs = six.text_type(int(time.time() * 1000000))[-6:]
if salt.utils.platform.is_windows():
# ':' is an illegal filesystem path character on Windows
stamp = time.strftime('%a_%b_%d_%H-%M-%S_%Y')
else:
stamp = time.strftime('%a_%b_%d_%H:%M:%S_%Y')
stamp = '{0}{1}_{2}'.format(stamp[:-4], msecs, stamp[-4:])
bkpath = os.path.join(bkroot,
src_dir,
'{0}_{1}'.format(bname, stamp))
if not os.path.isdir(os.path.dirname(bkpath)):
os.makedirs(os.path.dirname(bkpath))
shutil.copyfile(path, bkpath)
if not salt.utils.platform.is_windows():
os.chown(bkpath, fstat.st_uid, fstat.st_gid)
os.chmod(bkpath, fstat.st_mode) | [
"def",
"backup_minion",
"(",
"path",
",",
"bkroot",
")",
":",
"dname",
",",
"bname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"src_dir",
"=",
"dname",
"."... | Backup a file on the minion | [
"Backup",
"a",
"file",
"on",
"the",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L776-L802 | train |
saltstack/salt | salt/utils/files.py | get_encoding | def get_encoding(path):
'''
Detect a file's encoding using the following:
- Check for Byte Order Marks (BOM)
- Check for UTF-8 Markers
- Check System Encoding
- Check for ascii
Args:
path (str): The path to the file to check
Returns:
str: The encoding of the file
Raises:
CommandExecutionError: If the encoding cannot be detected
'''
def check_ascii(_data):
# If all characters can be decoded to ASCII, then it's ASCII
try:
_data.decode('ASCII')
log.debug('Found ASCII')
except UnicodeDecodeError:
return False
else:
return True
def check_bom(_data):
# Supported Python Codecs
# https://docs.python.org/2/library/codecs.html
# https://docs.python.org/3/library/codecs.html
boms = [
('UTF-32-BE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF32_BE)),
('UTF-32-LE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF32_LE)),
('UTF-16-BE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF16_BE)),
('UTF-16-LE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF16_LE)),
('UTF-8', salt.utils.stringutils.to_bytes(codecs.BOM_UTF8)),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x38\x2D')),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x38')),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x39')),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x2b')),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x2f')),
]
for _encoding, bom in boms:
if _data.startswith(bom):
log.debug('Found BOM for %s', _encoding)
return _encoding
return False
def check_utf8_markers(_data):
try:
decoded = _data.decode('UTF-8')
except UnicodeDecodeError:
return False
else:
# Reject surrogate characters in Py2 (Py3 behavior)
if six.PY2:
for char in decoded:
if 0xD800 <= ord(char) <= 0xDFFF:
return False
return True
def check_system_encoding(_data):
try:
_data.decode(__salt_system_encoding__)
except UnicodeDecodeError:
return False
else:
return True
if not os.path.isfile(path):
raise CommandExecutionError('Not a file')
try:
with fopen(path, 'rb') as fp_:
data = fp_.read(2048)
except os.error:
raise CommandExecutionError('Failed to open file')
# Check for Unicode BOM
encoding = check_bom(data)
if encoding:
return encoding
# Check for UTF-8 markers
if check_utf8_markers(data):
return 'UTF-8'
# Check system encoding
if check_system_encoding(data):
return __salt_system_encoding__
# Check for ASCII first
if check_ascii(data):
return 'ASCII'
raise CommandExecutionError('Could not detect file encoding') | python | def get_encoding(path):
'''
Detect a file's encoding using the following:
- Check for Byte Order Marks (BOM)
- Check for UTF-8 Markers
- Check System Encoding
- Check for ascii
Args:
path (str): The path to the file to check
Returns:
str: The encoding of the file
Raises:
CommandExecutionError: If the encoding cannot be detected
'''
def check_ascii(_data):
# If all characters can be decoded to ASCII, then it's ASCII
try:
_data.decode('ASCII')
log.debug('Found ASCII')
except UnicodeDecodeError:
return False
else:
return True
def check_bom(_data):
# Supported Python Codecs
# https://docs.python.org/2/library/codecs.html
# https://docs.python.org/3/library/codecs.html
boms = [
('UTF-32-BE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF32_BE)),
('UTF-32-LE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF32_LE)),
('UTF-16-BE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF16_BE)),
('UTF-16-LE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF16_LE)),
('UTF-8', salt.utils.stringutils.to_bytes(codecs.BOM_UTF8)),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x38\x2D')),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x38')),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x39')),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x2b')),
('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x2f')),
]
for _encoding, bom in boms:
if _data.startswith(bom):
log.debug('Found BOM for %s', _encoding)
return _encoding
return False
def check_utf8_markers(_data):
try:
decoded = _data.decode('UTF-8')
except UnicodeDecodeError:
return False
else:
# Reject surrogate characters in Py2 (Py3 behavior)
if six.PY2:
for char in decoded:
if 0xD800 <= ord(char) <= 0xDFFF:
return False
return True
def check_system_encoding(_data):
try:
_data.decode(__salt_system_encoding__)
except UnicodeDecodeError:
return False
else:
return True
if not os.path.isfile(path):
raise CommandExecutionError('Not a file')
try:
with fopen(path, 'rb') as fp_:
data = fp_.read(2048)
except os.error:
raise CommandExecutionError('Failed to open file')
# Check for Unicode BOM
encoding = check_bom(data)
if encoding:
return encoding
# Check for UTF-8 markers
if check_utf8_markers(data):
return 'UTF-8'
# Check system encoding
if check_system_encoding(data):
return __salt_system_encoding__
# Check for ASCII first
if check_ascii(data):
return 'ASCII'
raise CommandExecutionError('Could not detect file encoding') | [
"def",
"get_encoding",
"(",
"path",
")",
":",
"def",
"check_ascii",
"(",
"_data",
")",
":",
"# If all characters can be decoded to ASCII, then it's ASCII",
"try",
":",
"_data",
".",
"decode",
"(",
"'ASCII'",
")",
"log",
".",
"debug",
"(",
"'Found ASCII'",
")",
"... | Detect a file's encoding using the following:
- Check for Byte Order Marks (BOM)
- Check for UTF-8 Markers
- Check System Encoding
- Check for ascii
Args:
path (str): The path to the file to check
Returns:
str: The encoding of the file
Raises:
CommandExecutionError: If the encoding cannot be detected | [
"Detect",
"a",
"file",
"s",
"encoding",
"using",
"the",
"following",
":",
"-",
"Check",
"for",
"Byte",
"Order",
"Marks",
"(",
"BOM",
")",
"-",
"Check",
"for",
"UTF",
"-",
"8",
"Markers",
"-",
"Check",
"System",
"Encoding",
"-",
"Check",
"for",
"ascii"
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L805-L901 | train |
saltstack/salt | salt/states/grafana4_dashboard.py | absent | def absent(name, orgname=None, profile='grafana'):
'''
Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
orgname
Name of the organization in which the dashboard should be present.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if isinstance(profile, six.string_types):
profile = __salt__['config.option'](profile)
existing_dashboard = __salt__['grafana4.get_dashboard'](
name, orgname, profile)
if existing_dashboard:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dashboard {0} is set to be deleted.'.format(name)
return ret
__salt__['grafana4.delete_dashboard'](name, profile=profile)
ret['comment'] = 'Dashboard {0} deleted.'.format(name)
ret['changes']['new'] = 'Dashboard {0} deleted.'.format(name)
return ret
ret['comment'] = 'Dashboard absent'
return ret | python | def absent(name, orgname=None, profile='grafana'):
'''
Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
orgname
Name of the organization in which the dashboard should be present.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if isinstance(profile, six.string_types):
profile = __salt__['config.option'](profile)
existing_dashboard = __salt__['grafana4.get_dashboard'](
name, orgname, profile)
if existing_dashboard:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dashboard {0} is set to be deleted.'.format(name)
return ret
__salt__['grafana4.delete_dashboard'](name, profile=profile)
ret['comment'] = 'Dashboard {0} deleted.'.format(name)
ret['changes']['new'] = 'Dashboard {0} deleted.'.format(name)
return ret
ret['comment'] = 'Dashboard absent'
return ret | [
"def",
"absent",
"(",
"name",
",",
"orgname",
"=",
"None",
",",
"profile",
"=",
"'grafana'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
... | Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
orgname
Name of the organization in which the dashboard should be present.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'. | [
"Ensure",
"the",
"named",
"grafana",
"dashboard",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana4_dashboard.py#L212-L245 | train |
saltstack/salt | salt/grains/zfs.py | _zfs_pool_data | def _zfs_pool_data():
'''
Provide grains about zpools
'''
grains = {}
# collect zpool data
zpool_list_cmd = __utils__['zfs.zpool_command'](
'list',
flags=['-H'],
opts={'-o': 'name,size'},
)
for zpool in __salt__['cmd.run'](zpool_list_cmd, ignore_retcode=True).splitlines():
if 'zpool' not in grains:
grains['zpool'] = {}
zpool = zpool.split()
grains['zpool'][zpool[0]] = __utils__['zfs.to_size'](zpool[1], False)
# return grain data
return grains | python | def _zfs_pool_data():
'''
Provide grains about zpools
'''
grains = {}
# collect zpool data
zpool_list_cmd = __utils__['zfs.zpool_command'](
'list',
flags=['-H'],
opts={'-o': 'name,size'},
)
for zpool in __salt__['cmd.run'](zpool_list_cmd, ignore_retcode=True).splitlines():
if 'zpool' not in grains:
grains['zpool'] = {}
zpool = zpool.split()
grains['zpool'][zpool[0]] = __utils__['zfs.to_size'](zpool[1], False)
# return grain data
return grains | [
"def",
"_zfs_pool_data",
"(",
")",
":",
"grains",
"=",
"{",
"}",
"# collect zpool data",
"zpool_list_cmd",
"=",
"__utils__",
"[",
"'zfs.zpool_command'",
"]",
"(",
"'list'",
",",
"flags",
"=",
"[",
"'-H'",
"]",
",",
"opts",
"=",
"{",
"'-o'",
":",
"'name,siz... | Provide grains about zpools | [
"Provide",
"grains",
"about",
"zpools"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/zfs.py#L54-L73 | train |
saltstack/salt | salt/grains/zfs.py | zfs | def zfs():
'''
Provide grains for zfs/zpool
'''
grains = {}
grains['zfs_support'] = __utils__['zfs.is_supported']()
grains['zfs_feature_flags'] = __utils__['zfs.has_feature_flags']()
if grains['zfs_support']:
grains = salt.utils.dictupdate.update(grains, _zfs_pool_data(), merge_lists=True)
return grains | python | def zfs():
'''
Provide grains for zfs/zpool
'''
grains = {}
grains['zfs_support'] = __utils__['zfs.is_supported']()
grains['zfs_feature_flags'] = __utils__['zfs.has_feature_flags']()
if grains['zfs_support']:
grains = salt.utils.dictupdate.update(grains, _zfs_pool_data(), merge_lists=True)
return grains | [
"def",
"zfs",
"(",
")",
":",
"grains",
"=",
"{",
"}",
"grains",
"[",
"'zfs_support'",
"]",
"=",
"__utils__",
"[",
"'zfs.is_supported'",
"]",
"(",
")",
"grains",
"[",
"'zfs_feature_flags'",
"]",
"=",
"__utils__",
"[",
"'zfs.has_feature_flags'",
"]",
"(",
")... | Provide grains for zfs/zpool | [
"Provide",
"grains",
"for",
"zfs",
"/",
"zpool"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/zfs.py#L76-L86 | train |
saltstack/salt | salt/runners/network.py | wollist | def wollist(maclist, bcast='255.255.255.255', destport=9):
'''
Send a "Magic Packet" to wake up a list of Minions.
This list must contain one MAC hardware address per line
CLI Example:
.. code-block:: bash
salt-run network.wollist '/path/to/maclist'
salt-run network.wollist '/path/to/maclist' 255.255.255.255 7
salt-run network.wollist '/path/to/maclist' 255.255.255.255 7
'''
ret = []
try:
with salt.utils.files.fopen(maclist, 'r') as ifile:
for mac in ifile:
mac = salt.utils.stringutils.to_unicode(mac).strip()
wol(mac, bcast, destport)
print('Waking up {0}'.format(mac))
ret.append(mac)
except Exception as err:
__jid_event__.fire_event({'error': 'Failed to open the MAC file. Error: {0}'.format(err)}, 'progress')
return []
return ret | python | def wollist(maclist, bcast='255.255.255.255', destport=9):
'''
Send a "Magic Packet" to wake up a list of Minions.
This list must contain one MAC hardware address per line
CLI Example:
.. code-block:: bash
salt-run network.wollist '/path/to/maclist'
salt-run network.wollist '/path/to/maclist' 255.255.255.255 7
salt-run network.wollist '/path/to/maclist' 255.255.255.255 7
'''
ret = []
try:
with salt.utils.files.fopen(maclist, 'r') as ifile:
for mac in ifile:
mac = salt.utils.stringutils.to_unicode(mac).strip()
wol(mac, bcast, destport)
print('Waking up {0}'.format(mac))
ret.append(mac)
except Exception as err:
__jid_event__.fire_event({'error': 'Failed to open the MAC file. Error: {0}'.format(err)}, 'progress')
return []
return ret | [
"def",
"wollist",
"(",
"maclist",
",",
"bcast",
"=",
"'255.255.255.255'",
",",
"destport",
"=",
"9",
")",
":",
"ret",
"=",
"[",
"]",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"maclist",
",",
"'r'",
")",
"as",
"ifile... | Send a "Magic Packet" to wake up a list of Minions.
This list must contain one MAC hardware address per line
CLI Example:
.. code-block:: bash
salt-run network.wollist '/path/to/maclist'
salt-run network.wollist '/path/to/maclist' 255.255.255.255 7
salt-run network.wollist '/path/to/maclist' 255.255.255.255 7 | [
"Send",
"a",
"Magic",
"Packet",
"to",
"wake",
"up",
"a",
"list",
"of",
"Minions",
".",
"This",
"list",
"must",
"contain",
"one",
"MAC",
"hardware",
"address",
"per",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/network.py#L19-L43 | train |
saltstack/salt | salt/runners/network.py | wol | def wol(mac, bcast='255.255.255.255', destport=9):
'''
Send a "Magic Packet" to wake up a Minion
CLI Example:
.. code-block:: bash
salt-run network.wol 08-00-27-13-69-77
salt-run network.wol 080027136977 255.255.255.255 7
salt-run network.wol 08:00:27:13:69:77 255.255.255.255 7
'''
dest = salt.utils.network.mac_str_to_bytes(mac)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(b'\xff' * 6 + dest * 16, (bcast, int(destport)))
return True | python | def wol(mac, bcast='255.255.255.255', destport=9):
'''
Send a "Magic Packet" to wake up a Minion
CLI Example:
.. code-block:: bash
salt-run network.wol 08-00-27-13-69-77
salt-run network.wol 080027136977 255.255.255.255 7
salt-run network.wol 08:00:27:13:69:77 255.255.255.255 7
'''
dest = salt.utils.network.mac_str_to_bytes(mac)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(b'\xff' * 6 + dest * 16, (bcast, int(destport)))
return True | [
"def",
"wol",
"(",
"mac",
",",
"bcast",
"=",
"'255.255.255.255'",
",",
"destport",
"=",
"9",
")",
":",
"dest",
"=",
"salt",
".",
"utils",
".",
"network",
".",
"mac_str_to_bytes",
"(",
"mac",
")",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
"... | Send a "Magic Packet" to wake up a Minion
CLI Example:
.. code-block:: bash
salt-run network.wol 08-00-27-13-69-77
salt-run network.wol 080027136977 255.255.255.255 7
salt-run network.wol 08:00:27:13:69:77 255.255.255.255 7 | [
"Send",
"a",
"Magic",
"Packet",
"to",
"wake",
"up",
"a",
"Minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/network.py#L46-L62 | train |
saltstack/salt | salt/runners/network.py | wolmatch | def wolmatch(tgt, tgt_type='glob', bcast='255.255.255.255', destport=9):
'''
Send a "Magic Packet" to wake up Minions that are matched in the grains cache
CLI Example:
.. code-block:: bash
salt-run network.wolmatch minion_id
salt-run network.wolmatch 192.168.0.0/16 tgt_type='ipcidr' bcast=255.255.255.255 destport=7
'''
ret = []
minions = __salt__['cache.grains'](tgt, tgt_type)
for minion in minions:
for iface, mac in minion['hwaddr_interfaces'].items():
if iface == 'lo':
continue
mac = mac.strip()
wol(mac, bcast, destport)
log.info('Waking up %s', mac)
ret.append(mac)
return ret | python | def wolmatch(tgt, tgt_type='glob', bcast='255.255.255.255', destport=9):
'''
Send a "Magic Packet" to wake up Minions that are matched in the grains cache
CLI Example:
.. code-block:: bash
salt-run network.wolmatch minion_id
salt-run network.wolmatch 192.168.0.0/16 tgt_type='ipcidr' bcast=255.255.255.255 destport=7
'''
ret = []
minions = __salt__['cache.grains'](tgt, tgt_type)
for minion in minions:
for iface, mac in minion['hwaddr_interfaces'].items():
if iface == 'lo':
continue
mac = mac.strip()
wol(mac, bcast, destport)
log.info('Waking up %s', mac)
ret.append(mac)
return ret | [
"def",
"wolmatch",
"(",
"tgt",
",",
"tgt_type",
"=",
"'glob'",
",",
"bcast",
"=",
"'255.255.255.255'",
",",
"destport",
"=",
"9",
")",
":",
"ret",
"=",
"[",
"]",
"minions",
"=",
"__salt__",
"[",
"'cache.grains'",
"]",
"(",
"tgt",
",",
"tgt_type",
")",
... | Send a "Magic Packet" to wake up Minions that are matched in the grains cache
CLI Example:
.. code-block:: bash
salt-run network.wolmatch minion_id
salt-run network.wolmatch 192.168.0.0/16 tgt_type='ipcidr' bcast=255.255.255.255 destport=7 | [
"Send",
"a",
"Magic",
"Packet",
"to",
"wake",
"up",
"Minions",
"that",
"are",
"matched",
"in",
"the",
"grains",
"cache"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/network.py#L65-L86 | train |
saltstack/salt | salt/utils/memcached.py | get_conn | def get_conn(opts, profile=None, host=None, port=None):
'''
Return a conn object for accessing memcached
'''
if not (host and port):
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
opts_merged.update(opts_pillar)
opts_merged.update(opts)
if profile:
conf = opts_merged.get(profile, {})
else:
conf = opts_merged
host = conf.get('memcached.host', DEFAULT_HOST)
port = conf.get('memcached.port', DEFAULT_PORT)
if not six.text_type(port).isdigit():
raise SaltInvocationError('port must be an integer')
if HAS_LIBS:
return memcache.Client(['{0}:{1}'.format(host, port)])
else:
raise CommandExecutionError(
'(unable to import memcache, '
'module most likely not installed)'
) | python | def get_conn(opts, profile=None, host=None, port=None):
'''
Return a conn object for accessing memcached
'''
if not (host and port):
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
opts_merged.update(opts_pillar)
opts_merged.update(opts)
if profile:
conf = opts_merged.get(profile, {})
else:
conf = opts_merged
host = conf.get('memcached.host', DEFAULT_HOST)
port = conf.get('memcached.port', DEFAULT_PORT)
if not six.text_type(port).isdigit():
raise SaltInvocationError('port must be an integer')
if HAS_LIBS:
return memcache.Client(['{0}:{1}'.format(host, port)])
else:
raise CommandExecutionError(
'(unable to import memcache, '
'module most likely not installed)'
) | [
"def",
"get_conn",
"(",
"opts",
",",
"profile",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"not",
"(",
"host",
"and",
"port",
")",
":",
"opts_pillar",
"=",
"opts",
".",
"get",
"(",
"'pillar'",
",",
"{",
"}",
... | Return a conn object for accessing memcached | [
"Return",
"a",
"conn",
"object",
"for",
"accessing",
"memcached"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/memcached.py#L77-L107 | train |
saltstack/salt | salt/utils/memcached.py | set_ | def set_(conn,
key,
value,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Set a key on the memcached server, overwriting the value if it exists.
'''
if not isinstance(time, integer_types):
raise SaltInvocationError('\'time\' must be an integer')
if not isinstance(min_compress_len, integer_types):
raise SaltInvocationError('\'min_compress_len\' must be an integer')
_check_stats(conn)
return conn.set(key, value, time, min_compress_len) | python | def set_(conn,
key,
value,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Set a key on the memcached server, overwriting the value if it exists.
'''
if not isinstance(time, integer_types):
raise SaltInvocationError('\'time\' must be an integer')
if not isinstance(min_compress_len, integer_types):
raise SaltInvocationError('\'min_compress_len\' must be an integer')
_check_stats(conn)
return conn.set(key, value, time, min_compress_len) | [
"def",
"set_",
"(",
"conn",
",",
"key",
",",
"value",
",",
"time",
"=",
"DEFAULT_TIME",
",",
"min_compress_len",
"=",
"DEFAULT_MIN_COMPRESS_LEN",
")",
":",
"if",
"not",
"isinstance",
"(",
"time",
",",
"integer_types",
")",
":",
"raise",
"SaltInvocationError",
... | Set a key on the memcached server, overwriting the value if it exists. | [
"Set",
"a",
"key",
"on",
"the",
"memcached",
"server",
"overwriting",
"the",
"value",
"if",
"it",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/memcached.py#L123-L136 | train |
saltstack/salt | salt/modules/glassfish.py | _get_auth | def _get_auth(username, password):
'''
Returns the HTTP auth header
'''
if username and password:
return requests.auth.HTTPBasicAuth(username, password)
else:
return None | python | def _get_auth(username, password):
'''
Returns the HTTP auth header
'''
if username and password:
return requests.auth.HTTPBasicAuth(username, password)
else:
return None | [
"def",
"_get_auth",
"(",
"username",
",",
"password",
")",
":",
"if",
"username",
"and",
"password",
":",
"return",
"requests",
".",
"auth",
".",
"HTTPBasicAuth",
"(",
"username",
",",
"password",
")",
"else",
":",
"return",
"None"
] | Returns the HTTP auth header | [
"Returns",
"the",
"HTTP",
"auth",
"header"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L51-L58 | train |
saltstack/salt | salt/modules/glassfish.py | _get_url | def _get_url(ssl, url, port, path):
'''
Returns the URL of the endpoint
'''
if ssl:
return 'https://{0}:{1}/management/domain/{2}'.format(url, port, path)
else:
return 'http://{0}:{1}/management/domain/{2}'.format(url, port, path) | python | def _get_url(ssl, url, port, path):
'''
Returns the URL of the endpoint
'''
if ssl:
return 'https://{0}:{1}/management/domain/{2}'.format(url, port, path)
else:
return 'http://{0}:{1}/management/domain/{2}'.format(url, port, path) | [
"def",
"_get_url",
"(",
"ssl",
",",
"url",
",",
"port",
",",
"path",
")",
":",
"if",
"ssl",
":",
"return",
"'https://{0}:{1}/management/domain/{2}'",
".",
"format",
"(",
"url",
",",
"port",
",",
"path",
")",
"else",
":",
"return",
"'http://{0}:{1}/management... | Returns the URL of the endpoint | [
"Returns",
"the",
"URL",
"of",
"the",
"endpoint"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L61-L68 | train |
saltstack/salt | salt/modules/glassfish.py | _clean_data | def _clean_data(data):
'''
Removes SaltStack params from **kwargs
'''
for key in list(data):
if key.startswith('__pub'):
del data[key]
return data | python | def _clean_data(data):
'''
Removes SaltStack params from **kwargs
'''
for key in list(data):
if key.startswith('__pub'):
del data[key]
return data | [
"def",
"_clean_data",
"(",
"data",
")",
":",
"for",
"key",
"in",
"list",
"(",
"data",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'__pub'",
")",
":",
"del",
"data",
"[",
"key",
"]",
"return",
"data"
] | Removes SaltStack params from **kwargs | [
"Removes",
"SaltStack",
"params",
"from",
"**",
"kwargs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L78-L85 | train |
saltstack/salt | salt/modules/glassfish.py | _api_response | def _api_response(response):
'''
Check response status code + success_code returned by glassfish
'''
if response.status_code == 404:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('Element doesn\'t exists')
if response.status_code == 401:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('Bad username or password')
elif response.status_code == 200 or response.status_code == 500:
try:
data = salt.utils.json.loads(response.content)
if data['exit_code'] != 'SUCCESS':
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError(data['message'])
return data
except ValueError:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('The server returned no data')
else:
response.raise_for_status() | python | def _api_response(response):
'''
Check response status code + success_code returned by glassfish
'''
if response.status_code == 404:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('Element doesn\'t exists')
if response.status_code == 401:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('Bad username or password')
elif response.status_code == 200 or response.status_code == 500:
try:
data = salt.utils.json.loads(response.content)
if data['exit_code'] != 'SUCCESS':
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError(data['message'])
return data
except ValueError:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('The server returned no data')
else:
response.raise_for_status() | [
"def",
"_api_response",
"(",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"404",
":",
"__context__",
"[",
"'retcode'",
"]",
"=",
"salt",
".",
"defaults",
".",
"exitcodes",
".",
"SALT_BUILD_FAIL",
"raise",
"CommandExecutionError",
"(",
"'El... | Check response status code + success_code returned by glassfish | [
"Check",
"response",
"status",
"code",
"+",
"success_code",
"returned",
"by",
"glassfish"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L88-L109 | train |
saltstack/salt | salt/modules/glassfish.py | _api_get | def _api_get(path, server=None):
'''
Do a GET request to the API
'''
server = _get_server(server)
response = requests.get(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password']),
headers=_get_headers(),
verify=False
)
return _api_response(response) | python | def _api_get(path, server=None):
'''
Do a GET request to the API
'''
server = _get_server(server)
response = requests.get(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password']),
headers=_get_headers(),
verify=False
)
return _api_response(response) | [
"def",
"_api_get",
"(",
"path",
",",
"server",
"=",
"None",
")",
":",
"server",
"=",
"_get_server",
"(",
"server",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"_get_url",
"(",
"server",
"[",
"'ssl'",
"]",
",",
"server",
"[",
"'url'... | Do a GET request to the API | [
"Do",
"a",
"GET",
"request",
"to",
"the",
"API"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L112-L123 | train |
saltstack/salt | salt/modules/glassfish.py | _api_post | def _api_post(path, data, server=None):
'''
Do a POST request to the API
'''
server = _get_server(server)
response = requests.post(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password']),
headers=_get_headers(),
data=salt.utils.json.dumps(data),
verify=False
)
return _api_response(response) | python | def _api_post(path, data, server=None):
'''
Do a POST request to the API
'''
server = _get_server(server)
response = requests.post(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password']),
headers=_get_headers(),
data=salt.utils.json.dumps(data),
verify=False
)
return _api_response(response) | [
"def",
"_api_post",
"(",
"path",
",",
"data",
",",
"server",
"=",
"None",
")",
":",
"server",
"=",
"_get_server",
"(",
"server",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
"=",
"_get_url",
"(",
"server",
"[",
"'ssl'",
"]",
",",
"serve... | Do a POST request to the API | [
"Do",
"a",
"POST",
"request",
"to",
"the",
"API"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L126-L138 | train |
saltstack/salt | salt/modules/glassfish.py | _api_delete | def _api_delete(path, data, server=None):
'''
Do a DELETE request to the API
'''
server = _get_server(server)
response = requests.delete(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password']),
headers=_get_headers(),
params=data,
verify=False
)
return _api_response(response) | python | def _api_delete(path, data, server=None):
'''
Do a DELETE request to the API
'''
server = _get_server(server)
response = requests.delete(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password']),
headers=_get_headers(),
params=data,
verify=False
)
return _api_response(response) | [
"def",
"_api_delete",
"(",
"path",
",",
"data",
",",
"server",
"=",
"None",
")",
":",
"server",
"=",
"_get_server",
"(",
"server",
")",
"response",
"=",
"requests",
".",
"delete",
"(",
"url",
"=",
"_get_url",
"(",
"server",
"[",
"'ssl'",
"]",
",",
"s... | Do a DELETE request to the API | [
"Do",
"a",
"DELETE",
"request",
"to",
"the",
"API"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L141-L153 | train |
saltstack/salt | salt/modules/glassfish.py | _enum_elements | def _enum_elements(name, server=None):
'''
Enum elements
'''
elements = []
data = _api_get(name, server)
if any(data['extraProperties']['childResources']):
for element in data['extraProperties']['childResources']:
elements.append(element)
return elements
return None | python | def _enum_elements(name, server=None):
'''
Enum elements
'''
elements = []
data = _api_get(name, server)
if any(data['extraProperties']['childResources']):
for element in data['extraProperties']['childResources']:
elements.append(element)
return elements
return None | [
"def",
"_enum_elements",
"(",
"name",
",",
"server",
"=",
"None",
")",
":",
"elements",
"=",
"[",
"]",
"data",
"=",
"_api_get",
"(",
"name",
",",
"server",
")",
"if",
"any",
"(",
"data",
"[",
"'extraProperties'",
"]",
"[",
"'childResources'",
"]",
")",... | Enum elements | [
"Enum",
"elements"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L157-L168 | train |
saltstack/salt | salt/modules/glassfish.py | _get_element_properties | def _get_element_properties(name, element_type, server=None):
'''
Get an element's properties
'''
properties = {}
data = _api_get('{0}/{1}/property'.format(element_type, name), server)
# Get properties into a dict
if any(data['extraProperties']['properties']):
for element in data['extraProperties']['properties']:
properties[element['name']] = element['value']
return properties
return {} | python | def _get_element_properties(name, element_type, server=None):
'''
Get an element's properties
'''
properties = {}
data = _api_get('{0}/{1}/property'.format(element_type, name), server)
# Get properties into a dict
if any(data['extraProperties']['properties']):
for element in data['extraProperties']['properties']:
properties[element['name']] = element['value']
return properties
return {} | [
"def",
"_get_element_properties",
"(",
"name",
",",
"element_type",
",",
"server",
"=",
"None",
")",
":",
"properties",
"=",
"{",
"}",
"data",
"=",
"_api_get",
"(",
"'{0}/{1}/property'",
".",
"format",
"(",
"element_type",
",",
"name",
")",
",",
"server",
... | Get an element's properties | [
"Get",
"an",
"element",
"s",
"properties"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L171-L183 | train |
saltstack/salt | salt/modules/glassfish.py | _get_element | def _get_element(name, element_type, server=None, with_properties=True):
'''
Get an element with or without properties
'''
element = {}
name = quote(name, safe='')
data = _api_get('{0}/{1}'.format(element_type, name), server)
# Format data, get properties if asked, and return the whole thing
if any(data['extraProperties']['entity']):
for key, value in data['extraProperties']['entity'].items():
element[key] = value
if with_properties:
element['properties'] = _get_element_properties(name, element_type)
return element
return None | python | def _get_element(name, element_type, server=None, with_properties=True):
'''
Get an element with or without properties
'''
element = {}
name = quote(name, safe='')
data = _api_get('{0}/{1}'.format(element_type, name), server)
# Format data, get properties if asked, and return the whole thing
if any(data['extraProperties']['entity']):
for key, value in data['extraProperties']['entity'].items():
element[key] = value
if with_properties:
element['properties'] = _get_element_properties(name, element_type)
return element
return None | [
"def",
"_get_element",
"(",
"name",
",",
"element_type",
",",
"server",
"=",
"None",
",",
"with_properties",
"=",
"True",
")",
":",
"element",
"=",
"{",
"}",
"name",
"=",
"quote",
"(",
"name",
",",
"safe",
"=",
"''",
")",
"data",
"=",
"_api_get",
"("... | Get an element with or without properties | [
"Get",
"an",
"element",
"with",
"or",
"without",
"properties"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L186-L201 | train |
saltstack/salt | salt/modules/glassfish.py | _create_element | def _create_element(name, element_type, data, server=None):
'''
Create a new element
'''
# Define property and id from name and properties + remove SaltStack parameters
if 'properties' in data:
data['property'] = ''
for key, value in data['properties'].items():
if not data['property']:
data['property'] += '{0}={1}'.format(key, value.replace(':', '\\:'))
else:
data['property'] += ':{0}={1}'.format(key, value.replace(':', '\\:'))
del data['properties']
# Send request
_api_post(element_type, _clean_data(data), server)
return unquote(name) | python | def _create_element(name, element_type, data, server=None):
'''
Create a new element
'''
# Define property and id from name and properties + remove SaltStack parameters
if 'properties' in data:
data['property'] = ''
for key, value in data['properties'].items():
if not data['property']:
data['property'] += '{0}={1}'.format(key, value.replace(':', '\\:'))
else:
data['property'] += ':{0}={1}'.format(key, value.replace(':', '\\:'))
del data['properties']
# Send request
_api_post(element_type, _clean_data(data), server)
return unquote(name) | [
"def",
"_create_element",
"(",
"name",
",",
"element_type",
",",
"data",
",",
"server",
"=",
"None",
")",
":",
"# Define property and id from name and properties + remove SaltStack parameters",
"if",
"'properties'",
"in",
"data",
":",
"data",
"[",
"'property'",
"]",
"... | Create a new element | [
"Create",
"a",
"new",
"element"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L204-L220 | train |
saltstack/salt | salt/modules/glassfish.py | _update_element | def _update_element(name, element_type, data, server=None):
'''
Update an element, including it's properties
'''
# Urlencode the name (names may have slashes)
name = quote(name, safe='')
# Update properties first
if 'properties' in data:
properties = []
for key, value in data['properties'].items():
properties.append({'name': key, 'value': value})
_api_post('{0}/{1}/property'.format(element_type, name), properties, server)
del data['properties']
# If the element only contained properties
if not data:
return unquote(name)
# Get the current data then merge updated data into it
update_data = _get_element(name, element_type, server, with_properties=False)
if update_data:
update_data.update(data)
else:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('Cannot update {0}'.format(name))
# Finally, update the element
_api_post('{0}/{1}'.format(element_type, name), _clean_data(update_data), server)
return unquote(name) | python | def _update_element(name, element_type, data, server=None):
'''
Update an element, including it's properties
'''
# Urlencode the name (names may have slashes)
name = quote(name, safe='')
# Update properties first
if 'properties' in data:
properties = []
for key, value in data['properties'].items():
properties.append({'name': key, 'value': value})
_api_post('{0}/{1}/property'.format(element_type, name), properties, server)
del data['properties']
# If the element only contained properties
if not data:
return unquote(name)
# Get the current data then merge updated data into it
update_data = _get_element(name, element_type, server, with_properties=False)
if update_data:
update_data.update(data)
else:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('Cannot update {0}'.format(name))
# Finally, update the element
_api_post('{0}/{1}'.format(element_type, name), _clean_data(update_data), server)
return unquote(name) | [
"def",
"_update_element",
"(",
"name",
",",
"element_type",
",",
"data",
",",
"server",
"=",
"None",
")",
":",
"# Urlencode the name (names may have slashes)",
"name",
"=",
"quote",
"(",
"name",
",",
"safe",
"=",
"''",
")",
"# Update properties first",
"if",
"'p... | Update an element, including it's properties | [
"Update",
"an",
"element",
"including",
"it",
"s",
"properties"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L223-L252 | train |
saltstack/salt | salt/modules/glassfish.py | _delete_element | def _delete_element(name, element_type, data, server=None):
'''
Delete an element
'''
_api_delete('{0}/{1}'.format(element_type, quote(name, safe='')), data, server)
return name | python | def _delete_element(name, element_type, data, server=None):
'''
Delete an element
'''
_api_delete('{0}/{1}'.format(element_type, quote(name, safe='')), data, server)
return name | [
"def",
"_delete_element",
"(",
"name",
",",
"element_type",
",",
"data",
",",
"server",
"=",
"None",
")",
":",
"_api_delete",
"(",
"'{0}/{1}'",
".",
"format",
"(",
"element_type",
",",
"quote",
"(",
"name",
",",
"safe",
"=",
"''",
")",
")",
",",
"data"... | Delete an element | [
"Delete",
"an",
"element"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L255-L260 | train |
saltstack/salt | salt/modules/glassfish.py | create_connector_c_pool | def create_connector_c_pool(name, server=None, **kwargs):
'''
Create a connection pool
'''
defaults = {
'connectionDefinitionName': 'javax.jms.ConnectionFactory',
'resourceAdapterName': 'jmsra',
'associateWithThread': False,
'connectionCreationRetryAttempts': 0,
'connectionCreationRetryIntervalInSeconds': 0,
'connectionLeakReclaim': False,
'connectionLeakTimeoutInSeconds': 0,
'description': '',
'failAllConnections': False,
'id': name,
'idleTimeoutInSeconds': 300,
'isConnectionValidationRequired': False,
'lazyConnectionAssociation': False,
'lazyConnectionEnlistment': False,
'matchConnections': True,
'maxConnectionUsageCount': 0,
'maxPoolSize': 32,
'maxWaitTimeInMillis': 60000,
'ping': False,
'poolResizeQuantity': 2,
'pooling': True,
'steadyPoolSize': 8,
'target': 'server',
'transactionSupport': '',
'validateAtmostOncePeriodInSeconds': 0
}
# Data = defaults + merge kwargs + remove salt
data = defaults
data.update(kwargs)
# Check TransactionSupport against acceptable values
if data['transactionSupport'] and data['transactionSupport'] not in (
'XATransaction',
'LocalTransaction',
'NoTransaction'
):
raise CommandExecutionError('Invalid transaction support')
return _create_element(name, 'resources/connector-connection-pool', data, server) | python | def create_connector_c_pool(name, server=None, **kwargs):
'''
Create a connection pool
'''
defaults = {
'connectionDefinitionName': 'javax.jms.ConnectionFactory',
'resourceAdapterName': 'jmsra',
'associateWithThread': False,
'connectionCreationRetryAttempts': 0,
'connectionCreationRetryIntervalInSeconds': 0,
'connectionLeakReclaim': False,
'connectionLeakTimeoutInSeconds': 0,
'description': '',
'failAllConnections': False,
'id': name,
'idleTimeoutInSeconds': 300,
'isConnectionValidationRequired': False,
'lazyConnectionAssociation': False,
'lazyConnectionEnlistment': False,
'matchConnections': True,
'maxConnectionUsageCount': 0,
'maxPoolSize': 32,
'maxWaitTimeInMillis': 60000,
'ping': False,
'poolResizeQuantity': 2,
'pooling': True,
'steadyPoolSize': 8,
'target': 'server',
'transactionSupport': '',
'validateAtmostOncePeriodInSeconds': 0
}
# Data = defaults + merge kwargs + remove salt
data = defaults
data.update(kwargs)
# Check TransactionSupport against acceptable values
if data['transactionSupport'] and data['transactionSupport'] not in (
'XATransaction',
'LocalTransaction',
'NoTransaction'
):
raise CommandExecutionError('Invalid transaction support')
return _create_element(name, 'resources/connector-connection-pool', data, server) | [
"def",
"create_connector_c_pool",
"(",
"name",
",",
"server",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"{",
"'connectionDefinitionName'",
":",
"'javax.jms.ConnectionFactory'",
",",
"'resourceAdapterName'",
":",
"'jmsra'",
",",
"'associateWith... | Create a connection pool | [
"Create",
"a",
"connection",
"pool"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L278-L322 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.