repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/systemd_service.py | _systemctl_status | def _systemctl_status(name):
'''
Helper function which leverages __context__ to keep from running 'systemctl
status' more than once.
'''
contextkey = 'systemd._systemctl_status.%s' % name
if contextkey in __context__:
return __context__[contextkey]
__context__[contextkey] = __salt__['cmd.run_all'](
_systemctl_cmd('status', name),
python_shell=False,
redirect_stderr=True,
ignore_retcode=True
)
return __context__[contextkey] | python | def _systemctl_status(name):
'''
Helper function which leverages __context__ to keep from running 'systemctl
status' more than once.
'''
contextkey = 'systemd._systemctl_status.%s' % name
if contextkey in __context__:
return __context__[contextkey]
__context__[contextkey] = __salt__['cmd.run_all'](
_systemctl_cmd('status', name),
python_shell=False,
redirect_stderr=True,
ignore_retcode=True
)
return __context__[contextkey] | [
"def",
"_systemctl_status",
"(",
"name",
")",
":",
"contextkey",
"=",
"'systemd._systemctl_status.%s'",
"%",
"name",
"if",
"contextkey",
"in",
"__context__",
":",
"return",
"__context__",
"[",
"contextkey",
"]",
"__context__",
"[",
"contextkey",
"]",
"=",
"__salt_... | Helper function which leverages __context__ to keep from running 'systemctl
status' more than once. | [
"Helper",
"function",
"which",
"leverages",
"__context__",
"to",
"keep",
"from",
"running",
"systemctl",
"status",
"more",
"than",
"once",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L349-L363 | train |
saltstack/salt | salt/modules/systemd_service.py | _sysv_enabled | def _sysv_enabled(name, root):
'''
A System-V style service is assumed disabled if the "startup" symlink
(starts with "S") to its script is found in /etc/init.d in the current
runlevel.
'''
# Find exact match (disambiguate matches like "S01anacron" for cron)
rc = _root('/etc/rc{}.d/S*{}'.format(_runlevel(), name), root)
for match in glob.glob(rc):
if re.match(r'S\d{,2}%s' % name, os.path.basename(match)):
return True
return False | python | def _sysv_enabled(name, root):
'''
A System-V style service is assumed disabled if the "startup" symlink
(starts with "S") to its script is found in /etc/init.d in the current
runlevel.
'''
# Find exact match (disambiguate matches like "S01anacron" for cron)
rc = _root('/etc/rc{}.d/S*{}'.format(_runlevel(), name), root)
for match in glob.glob(rc):
if re.match(r'S\d{,2}%s' % name, os.path.basename(match)):
return True
return False | [
"def",
"_sysv_enabled",
"(",
"name",
",",
"root",
")",
":",
"# Find exact match (disambiguate matches like \"S01anacron\" for cron)",
"rc",
"=",
"_root",
"(",
"'/etc/rc{}.d/S*{}'",
".",
"format",
"(",
"_runlevel",
"(",
")",
",",
"name",
")",
",",
"root",
")",
"for... | A System-V style service is assumed disabled if the "startup" symlink
(starts with "S") to its script is found in /etc/init.d in the current
runlevel. | [
"A",
"System",
"-",
"V",
"style",
"service",
"is",
"assumed",
"disabled",
"if",
"the",
"startup",
"symlink",
"(",
"starts",
"with",
"S",
")",
"to",
"its",
"script",
"is",
"found",
"in",
"/",
"etc",
"/",
"init",
".",
"d",
"in",
"the",
"current",
"runl... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L366-L377 | train |
saltstack/salt | salt/modules/systemd_service.py | _untracked_custom_unit_found | def _untracked_custom_unit_found(name, root=None):
'''
If the passed service name is not available, but a unit file exist in
/etc/systemd/system, return True. Otherwise, return False.
'''
system = _root('/etc/systemd/system', root)
unit_path = os.path.join(system, _canonical_unit_name(name))
return os.access(unit_path, os.R_OK) and not _check_available(name) | python | def _untracked_custom_unit_found(name, root=None):
'''
If the passed service name is not available, but a unit file exist in
/etc/systemd/system, return True. Otherwise, return False.
'''
system = _root('/etc/systemd/system', root)
unit_path = os.path.join(system, _canonical_unit_name(name))
return os.access(unit_path, os.R_OK) and not _check_available(name) | [
"def",
"_untracked_custom_unit_found",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"system",
"=",
"_root",
"(",
"'/etc/systemd/system'",
",",
"root",
")",
"unit_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"system",
",",
"_canonical_unit_name",
"(",... | If the passed service name is not available, but a unit file exist in
/etc/systemd/system, return True. Otherwise, return False. | [
"If",
"the",
"passed",
"service",
"name",
"is",
"not",
"available",
"but",
"a",
"unit",
"file",
"exist",
"in",
"/",
"etc",
"/",
"systemd",
"/",
"system",
"return",
"True",
".",
"Otherwise",
"return",
"False",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L380-L387 | train |
saltstack/salt | salt/modules/systemd_service.py | systemctl_reload | def systemctl_reload():
'''
.. versionadded:: 0.15.0
Reloads systemctl, an action needed whenever unit files are updated.
CLI Example:
.. code-block:: bash
salt '*' service.systemctl_reload
'''
out = __salt__['cmd.run_all'](
_systemctl_cmd('--system daemon-reload'),
python_shell=False,
redirect_stderr=True)
if out['retcode'] != 0:
raise CommandExecutionError(
'Problem performing systemctl daemon-reload: %s' % out['stdout']
)
_clear_context()
return True | python | def systemctl_reload():
'''
.. versionadded:: 0.15.0
Reloads systemctl, an action needed whenever unit files are updated.
CLI Example:
.. code-block:: bash
salt '*' service.systemctl_reload
'''
out = __salt__['cmd.run_all'](
_systemctl_cmd('--system daemon-reload'),
python_shell=False,
redirect_stderr=True)
if out['retcode'] != 0:
raise CommandExecutionError(
'Problem performing systemctl daemon-reload: %s' % out['stdout']
)
_clear_context()
return True | [
"def",
"systemctl_reload",
"(",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"_systemctl_cmd",
"(",
"'--system daemon-reload'",
")",
",",
"python_shell",
"=",
"False",
",",
"redirect_stderr",
"=",
"True",
")",
"if",
"out",
"[",
"'retcode'"... | .. versionadded:: 0.15.0
Reloads systemctl, an action needed whenever unit files are updated.
CLI Example:
.. code-block:: bash
salt '*' service.systemctl_reload | [
"..",
"versionadded",
"::",
"0",
".",
"15",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L399-L420 | train |
saltstack/salt | salt/modules/systemd_service.py | get_running | def get_running():
'''
Return a list of all running services, so far as systemd is concerned
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
# Get running systemd units
out = __salt__['cmd.run'](
_systemctl_cmd('--full --no-legend --no-pager'),
python_shell=False,
ignore_retcode=True)
for line in salt.utils.itertools.split(out, '\n'):
try:
comps = line.strip().split()
fullname = comps[0]
if len(comps) > 3:
active_state = comps[3]
except ValueError as exc:
log.error(exc)
continue
else:
if active_state != 'running':
continue
try:
unit_name, unit_type = fullname.rsplit('.', 1)
except ValueError:
continue
if unit_type in VALID_UNIT_TYPES:
ret.add(unit_name if unit_type == 'service' else fullname)
return sorted(ret) | python | def get_running():
'''
Return a list of all running services, so far as systemd is concerned
CLI Example:
.. code-block:: bash
salt '*' service.get_running
'''
ret = set()
# Get running systemd units
out = __salt__['cmd.run'](
_systemctl_cmd('--full --no-legend --no-pager'),
python_shell=False,
ignore_retcode=True)
for line in salt.utils.itertools.split(out, '\n'):
try:
comps = line.strip().split()
fullname = comps[0]
if len(comps) > 3:
active_state = comps[3]
except ValueError as exc:
log.error(exc)
continue
else:
if active_state != 'running':
continue
try:
unit_name, unit_type = fullname.rsplit('.', 1)
except ValueError:
continue
if unit_type in VALID_UNIT_TYPES:
ret.add(unit_name if unit_type == 'service' else fullname)
return sorted(ret) | [
"def",
"get_running",
"(",
")",
":",
"ret",
"=",
"set",
"(",
")",
"# Get running systemd units",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"_systemctl_cmd",
"(",
"'--full --no-legend --no-pager'",
")",
",",
"python_shell",
"=",
"False",
",",
"ignore_re... | Return a list of all running services, so far as systemd is concerned
CLI Example:
.. code-block:: bash
salt '*' service.get_running | [
"Return",
"a",
"list",
"of",
"all",
"running",
"services",
"so",
"far",
"as",
"systemd",
"is",
"concerned"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L423-L458 | train |
saltstack/salt | salt/modules/systemd_service.py | get_static | def get_static(root=None):
'''
.. versionadded:: 2015.8.5
Return a list of all static services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_static
'''
ret = set()
# Get static systemd units. Can't use --state=static here because it's
# not present until systemd 216.
out = __salt__['cmd.run'](
_systemctl_cmd('--full --no-legend --no-pager list-unit-files',
root=root),
python_shell=False,
ignore_retcode=True)
for line in salt.utils.itertools.split(out, '\n'):
try:
fullname, unit_state = line.strip().split(None, 1)
except ValueError:
continue
else:
if unit_state != 'static':
continue
try:
unit_name, unit_type = fullname.rsplit('.', 1)
except ValueError:
continue
if unit_type in VALID_UNIT_TYPES:
ret.add(unit_name if unit_type == 'service' else fullname)
# sysvinit services cannot be static
return sorted(ret) | python | def get_static(root=None):
'''
.. versionadded:: 2015.8.5
Return a list of all static services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_static
'''
ret = set()
# Get static systemd units. Can't use --state=static here because it's
# not present until systemd 216.
out = __salt__['cmd.run'](
_systemctl_cmd('--full --no-legend --no-pager list-unit-files',
root=root),
python_shell=False,
ignore_retcode=True)
for line in salt.utils.itertools.split(out, '\n'):
try:
fullname, unit_state = line.strip().split(None, 1)
except ValueError:
continue
else:
if unit_state != 'static':
continue
try:
unit_name, unit_type = fullname.rsplit('.', 1)
except ValueError:
continue
if unit_type in VALID_UNIT_TYPES:
ret.add(unit_name if unit_type == 'service' else fullname)
# sysvinit services cannot be static
return sorted(ret) | [
"def",
"get_static",
"(",
"root",
"=",
"None",
")",
":",
"ret",
"=",
"set",
"(",
")",
"# Get static systemd units. Can't use --state=static here because it's",
"# not present until systemd 216.",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"_systemctl_cmd",
"(",... | .. versionadded:: 2015.8.5
Return a list of all static services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_static | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"5"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L547-L586 | train |
saltstack/salt | salt/modules/systemd_service.py | get_all | def get_all(root=None):
'''
Return a list of all available services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = _get_systemd_services(root)
ret.update(set(_get_sysv_services(root, systemd_services=ret)))
return sorted(ret) | python | def get_all(root=None):
'''
Return a list of all available services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = _get_systemd_services(root)
ret.update(set(_get_sysv_services(root, systemd_services=ret)))
return sorted(ret) | [
"def",
"get_all",
"(",
"root",
"=",
"None",
")",
":",
"ret",
"=",
"_get_systemd_services",
"(",
"root",
")",
"ret",
".",
"update",
"(",
"set",
"(",
"_get_sysv_services",
"(",
"root",
",",
"systemd_services",
"=",
"ret",
")",
")",
")",
"return",
"sorted",... | Return a list of all available services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_all | [
"Return",
"a",
"list",
"of",
"all",
"available",
"services"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L589-L604 | train |
saltstack/salt | salt/modules/systemd_service.py | unmask_ | def unmask_(name, runtime=False, root=None):
'''
.. versionadded:: 2015.5.0
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Unmask the specified service with systemd
runtime : False
Set to ``True`` to unmask this service only until the next reboot
.. versionadded:: 2017.7.0
In previous versions, this function would remove whichever mask was
identified by running ``systemctl is-enabled`` on the service.
However, since it is possible to both have both indefinite and
runtime masks on a service simultaneously, this function now
removes a runtime mask only when this argument is set to ``True``,
and otherwise removes an indefinite mask.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.unmask foo
salt '*' service.unmask foo runtime=True
'''
_check_for_unit_changes(name)
if not masked(name, runtime, root=root):
log.debug('Service \'%s\' is not %smasked',
name, 'runtime-' if runtime else '')
return True
cmd = 'unmask --runtime' if runtime else 'unmask'
out = __salt__['cmd.run_all'](
_systemctl_cmd(cmd, name, systemd_scope=True, root=root),
python_shell=False,
redirect_stderr=True)
if out['retcode'] != 0:
raise CommandExecutionError('Failed to unmask service \'%s\'' % name)
return True | python | def unmask_(name, runtime=False, root=None):
'''
.. versionadded:: 2015.5.0
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Unmask the specified service with systemd
runtime : False
Set to ``True`` to unmask this service only until the next reboot
.. versionadded:: 2017.7.0
In previous versions, this function would remove whichever mask was
identified by running ``systemctl is-enabled`` on the service.
However, since it is possible to both have both indefinite and
runtime masks on a service simultaneously, this function now
removes a runtime mask only when this argument is set to ``True``,
and otherwise removes an indefinite mask.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.unmask foo
salt '*' service.unmask foo runtime=True
'''
_check_for_unit_changes(name)
if not masked(name, runtime, root=root):
log.debug('Service \'%s\' is not %smasked',
name, 'runtime-' if runtime else '')
return True
cmd = 'unmask --runtime' if runtime else 'unmask'
out = __salt__['cmd.run_all'](
_systemctl_cmd(cmd, name, systemd_scope=True, root=root),
python_shell=False,
redirect_stderr=True)
if out['retcode'] != 0:
raise CommandExecutionError('Failed to unmask service \'%s\'' % name)
return True | [
"def",
"unmask_",
"(",
"name",
",",
"runtime",
"=",
"False",
",",
"root",
"=",
"None",
")",
":",
"_check_for_unit_changes",
"(",
"name",
")",
"if",
"not",
"masked",
"(",
"name",
",",
"runtime",
",",
"root",
"=",
"root",
")",
":",
"log",
".",
"debug",... | .. versionadded:: 2015.5.0
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Unmask the specified service with systemd
runtime : False
Set to ``True`` to unmask this service only until the next reboot
.. versionadded:: 2017.7.0
In previous versions, this function would remove whichever mask was
identified by running ``systemctl is-enabled`` on the service.
However, since it is possible to both have both indefinite and
runtime masks on a service simultaneously, this function now
removes a runtime mask only when this argument is set to ``True``,
and otherwise removes an indefinite mask.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.unmask foo
salt '*' service.unmask foo runtime=True | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0",
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"12",
"2016",
".",
"3",
".",
"3",
"2016",
".",
"11",
".",
"0",
"On",
"minions",
"running",
"systemd",
">",
"=",
"205",
"systemd",
"-",
"r... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L641-L693 | train |
saltstack/salt | salt/modules/systemd_service.py | mask | def mask(name, runtime=False, root=None):
'''
.. versionadded:: 2015.5.0
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Mask the specified service with systemd
runtime : False
Set to ``True`` to mask this service only until the next reboot
.. versionadded:: 2015.8.5
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.mask foo
salt '*' service.mask foo runtime=True
'''
_check_for_unit_changes(name)
cmd = 'mask --runtime' if runtime else 'mask'
out = __salt__['cmd.run_all'](
_systemctl_cmd(cmd, name, systemd_scope=True, root=root),
python_shell=False,
redirect_stderr=True)
if out['retcode'] != 0:
raise CommandExecutionError(
'Failed to mask service \'%s\'' % name,
info=out['stdout']
)
return True | python | def mask(name, runtime=False, root=None):
'''
.. versionadded:: 2015.5.0
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Mask the specified service with systemd
runtime : False
Set to ``True`` to mask this service only until the next reboot
.. versionadded:: 2015.8.5
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.mask foo
salt '*' service.mask foo runtime=True
'''
_check_for_unit_changes(name)
cmd = 'mask --runtime' if runtime else 'mask'
out = __salt__['cmd.run_all'](
_systemctl_cmd(cmd, name, systemd_scope=True, root=root),
python_shell=False,
redirect_stderr=True)
if out['retcode'] != 0:
raise CommandExecutionError(
'Failed to mask service \'%s\'' % name,
info=out['stdout']
)
return True | [
"def",
"mask",
"(",
"name",
",",
"runtime",
"=",
"False",
",",
"root",
"=",
"None",
")",
":",
"_check_for_unit_changes",
"(",
"name",
")",
"cmd",
"=",
"'mask --runtime'",
"if",
"runtime",
"else",
"'mask'",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",... | .. versionadded:: 2015.5.0
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Mask the specified service with systemd
runtime : False
Set to ``True`` to mask this service only until the next reboot
.. versionadded:: 2015.8.5
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.mask foo
salt '*' service.mask foo runtime=True | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0",
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"12",
"2016",
".",
"3",
".",
"3",
"2016",
".",
"11",
".",
"0",
"On",
"minions",
"running",
"systemd",
">",
"=",
"205",
"systemd",
"-",
"r... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L696-L741 | train |
saltstack/salt | salt/modules/systemd_service.py | masked | def masked(name, runtime=False, root=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2015.8.5
The return data for this function has changed. If the service is
masked, the return value will now be the output of the ``systemctl
is-enabled`` command (so that a persistent mask can be distinguished
from a runtime mask). If the service is not masked, then ``False`` will
be returned.
.. versionchanged:: 2017.7.0
This function now returns a boolean telling the user whether a mask
specified by the new ``runtime`` argument is set. If ``runtime`` is
``False``, this function will return ``True`` if an indefinite mask is
set for the named service (otherwise ``False`` will be returned). If
``runtime`` is ``False``, this function will return ``True`` if a
runtime mask is set, otherwise ``False``.
Check whether or not a service is masked
runtime : False
Set to ``True`` to check for a runtime mask
.. versionadded:: 2017.7.0
In previous versions, this function would simply return the output
of ``systemctl is-enabled`` when the service was found to be
masked. However, since it is possible to both have both indefinite
and runtime masks on a service simultaneously, this function now
only checks for runtime masks if this argument is set to ``True``.
Otherwise, it will check for an indefinite mask.
root
Enable/disable/mask unit files in the specified root directory
CLI Examples:
.. code-block:: bash
salt '*' service.masked foo
salt '*' service.masked foo runtime=True
'''
_check_for_unit_changes(name)
root_dir = _root('/run' if runtime else '/etc', root)
link_path = os.path.join(root_dir,
'systemd',
'system',
_canonical_unit_name(name))
try:
return os.readlink(link_path) == '/dev/null'
except OSError as exc:
if exc.errno == errno.ENOENT:
log.trace(
'Path %s does not exist. This is normal if service \'%s\' is '
'not masked or does not exist.', link_path, name
)
elif exc.errno == errno.EINVAL:
log.error(
'Failed to check mask status for service %s. Path %s is a '
'file, not a symlink. This could be caused by changes in '
'systemd and is probably a bug in Salt. Please report this '
'to the developers.', name, link_path
)
return False | python | def masked(name, runtime=False, root=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2015.8.5
The return data for this function has changed. If the service is
masked, the return value will now be the output of the ``systemctl
is-enabled`` command (so that a persistent mask can be distinguished
from a runtime mask). If the service is not masked, then ``False`` will
be returned.
.. versionchanged:: 2017.7.0
This function now returns a boolean telling the user whether a mask
specified by the new ``runtime`` argument is set. If ``runtime`` is
``False``, this function will return ``True`` if an indefinite mask is
set for the named service (otherwise ``False`` will be returned). If
``runtime`` is ``False``, this function will return ``True`` if a
runtime mask is set, otherwise ``False``.
Check whether or not a service is masked
runtime : False
Set to ``True`` to check for a runtime mask
.. versionadded:: 2017.7.0
In previous versions, this function would simply return the output
of ``systemctl is-enabled`` when the service was found to be
masked. However, since it is possible to both have both indefinite
and runtime masks on a service simultaneously, this function now
only checks for runtime masks if this argument is set to ``True``.
Otherwise, it will check for an indefinite mask.
root
Enable/disable/mask unit files in the specified root directory
CLI Examples:
.. code-block:: bash
salt '*' service.masked foo
salt '*' service.masked foo runtime=True
'''
_check_for_unit_changes(name)
root_dir = _root('/run' if runtime else '/etc', root)
link_path = os.path.join(root_dir,
'systemd',
'system',
_canonical_unit_name(name))
try:
return os.readlink(link_path) == '/dev/null'
except OSError as exc:
if exc.errno == errno.ENOENT:
log.trace(
'Path %s does not exist. This is normal if service \'%s\' is '
'not masked or does not exist.', link_path, name
)
elif exc.errno == errno.EINVAL:
log.error(
'Failed to check mask status for service %s. Path %s is a '
'file, not a symlink. This could be caused by changes in '
'systemd and is probably a bug in Salt. Please report this '
'to the developers.', name, link_path
)
return False | [
"def",
"masked",
"(",
"name",
",",
"runtime",
"=",
"False",
",",
"root",
"=",
"None",
")",
":",
"_check_for_unit_changes",
"(",
"name",
")",
"root_dir",
"=",
"_root",
"(",
"'/run'",
"if",
"runtime",
"else",
"'/etc'",
",",
"root",
")",
"link_path",
"=",
... | .. versionadded:: 2015.8.0
.. versionchanged:: 2015.8.5
The return data for this function has changed. If the service is
masked, the return value will now be the output of the ``systemctl
is-enabled`` command (so that a persistent mask can be distinguished
from a runtime mask). If the service is not masked, then ``False`` will
be returned.
.. versionchanged:: 2017.7.0
This function now returns a boolean telling the user whether a mask
specified by the new ``runtime`` argument is set. If ``runtime`` is
``False``, this function will return ``True`` if an indefinite mask is
set for the named service (otherwise ``False`` will be returned). If
``runtime`` is ``False``, this function will return ``True`` if a
runtime mask is set, otherwise ``False``.
Check whether or not a service is masked
runtime : False
Set to ``True`` to check for a runtime mask
.. versionadded:: 2017.7.0
In previous versions, this function would simply return the output
of ``systemctl is-enabled`` when the service was found to be
masked. However, since it is possible to both have both indefinite
and runtime masks on a service simultaneously, this function now
only checks for runtime masks if this argument is set to ``True``.
Otherwise, it will check for an indefinite mask.
root
Enable/disable/mask unit files in the specified root directory
CLI Examples:
.. code-block:: bash
salt '*' service.masked foo
salt '*' service.masked foo runtime=True | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"5",
"The",
"return",
"data",
"for",
"this",
"function",
"has",
"changed",
".",
"If",
"the",
"service",
"is",
"masked",
"the",
"return",
"value... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L744-L805 | train |
saltstack/salt | salt/modules/systemd_service.py | stop | def stop(name, no_block=False):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Stop the specified service with systemd
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
_check_for_unit_changes(name)
# Using cmd.run_all instead of cmd.retcode here to make unit tests easier
return __salt__['cmd.run_all'](
_systemctl_cmd('stop', name, systemd_scope=True, no_block=no_block),
python_shell=False)['retcode'] == 0 | python | def stop(name, no_block=False):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Stop the specified service with systemd
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
_check_for_unit_changes(name)
# Using cmd.run_all instead of cmd.retcode here to make unit tests easier
return __salt__['cmd.run_all'](
_systemctl_cmd('stop', name, systemd_scope=True, no_block=no_block),
python_shell=False)['retcode'] == 0 | [
"def",
"stop",
"(",
"name",
",",
"no_block",
"=",
"False",
")",
":",
"_check_for_unit_changes",
"(",
"name",
")",
"# Using cmd.run_all instead of cmd.retcode here to make unit tests easier",
"return",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"_systemctl_cmd",
"(",
"'... | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Stop the specified service with systemd
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name> | [
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"12",
"2016",
".",
"3",
".",
"3",
"2016",
".",
"11",
".",
"0",
"On",
"minions",
"running",
"systemd",
">",
"=",
"205",
"systemd",
"-",
"run",
"(",
"1",
")",
"_",
"is",
"now",
"used",
"to",
"i... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L864-L894 | train |
saltstack/salt | salt/modules/systemd_service.py | restart | def restart(name, no_block=False, unmask=False, unmask_runtime=False):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Restart the specified service with systemd
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
Set to ``True`` to remove an indefinite mask before attempting to
restart the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
restarting. This behavior is no longer the default.
unmask_runtime : False
Set to ``True`` to remove a runtime mask before attempting to restart
the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
restarting. This behavior is no longer the default.
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
_check_for_unit_changes(name)
_check_unmask(name, unmask, unmask_runtime)
ret = __salt__['cmd.run_all'](
_systemctl_cmd('restart', name, systemd_scope=True, no_block=no_block),
python_shell=False)
if ret['retcode'] != 0:
# Instead of returning a bool, raise an exception so that we can
# include the error message in the return data. This helps give more
# information to the user in instances where the service is masked.
raise CommandExecutionError(_strip_scope(ret['stderr']))
return True | python | def restart(name, no_block=False, unmask=False, unmask_runtime=False):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Restart the specified service with systemd
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
Set to ``True`` to remove an indefinite mask before attempting to
restart the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
restarting. This behavior is no longer the default.
unmask_runtime : False
Set to ``True`` to remove a runtime mask before attempting to restart
the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
restarting. This behavior is no longer the default.
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
_check_for_unit_changes(name)
_check_unmask(name, unmask, unmask_runtime)
ret = __salt__['cmd.run_all'](
_systemctl_cmd('restart', name, systemd_scope=True, no_block=no_block),
python_shell=False)
if ret['retcode'] != 0:
# Instead of returning a bool, raise an exception so that we can
# include the error message in the return data. This helps give more
# information to the user in instances where the service is masked.
raise CommandExecutionError(_strip_scope(ret['stderr']))
return True | [
"def",
"restart",
"(",
"name",
",",
"no_block",
"=",
"False",
",",
"unmask",
"=",
"False",
",",
"unmask_runtime",
"=",
"False",
")",
":",
"_check_for_unit_changes",
"(",
"name",
")",
"_check_unmask",
"(",
"name",
",",
"unmask",
",",
"unmask_runtime",
")",
... | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Restart the specified service with systemd
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
Set to ``True`` to remove an indefinite mask before attempting to
restart the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
restarting. This behavior is no longer the default.
unmask_runtime : False
Set to ``True`` to remove a runtime mask before attempting to restart
the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
restarting. This behavior is no longer the default.
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name> | [
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"12",
"2016",
".",
"3",
".",
"3",
"2016",
".",
"11",
".",
"0",
"On",
"minions",
"running",
"systemd",
">",
"=",
"205",
"systemd",
"-",
"run",
"(",
"1",
")",
"_",
"is",
"now",
"used",
"to",
"i... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L897-L950 | train |
saltstack/salt | salt/modules/systemd_service.py | status | def status(name, sig=None): # pylint: disable=unused-argument
'''
Return the status for a service via systemd.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name> [service signature]
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
_check_for_unit_changes(service)
results[service] = __salt__['cmd.retcode'](
_systemctl_cmd('is-active', service),
python_shell=False,
ignore_retcode=True) == 0
if contains_globbing:
return results
return results[name] | python | def status(name, sig=None): # pylint: disable=unused-argument
'''
Return the status for a service via systemd.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name> [service signature]
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
_check_for_unit_changes(service)
results[service] = __salt__['cmd.retcode'](
_systemctl_cmd('is-active', service),
python_shell=False,
ignore_retcode=True) == 0
if contains_globbing:
return results
return results[name] | [
"def",
"status",
"(",
"name",
",",
"sig",
"=",
"None",
")",
":",
"# pylint: disable=unused-argument",
"contains_globbing",
"=",
"bool",
"(",
"re",
".",
"search",
"(",
"r'\\*|\\?|\\[.+\\]'",
",",
"name",
")",
")",
"if",
"contains_globbing",
":",
"services",
"="... | Return the status for a service via systemd.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Not implemented
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name> [service signature] | [
"Return",
"the",
"status",
"for",
"a",
"service",
"via",
"systemd",
".",
"If",
"the",
"name",
"contains",
"globbing",
"a",
"dict",
"mapping",
"service",
"name",
"to",
"True",
"/",
"False",
"values",
"is",
"returned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1070-L1107 | train |
saltstack/salt | salt/modules/systemd_service.py | enable | def enable(name, no_block=False, unmask=False, unmask_runtime=False,
root=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Enable the named service to start when the system boots
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
Set to ``True`` to remove an indefinite mask before attempting to
enable the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
enabling. This behavior is no longer the default.
unmask_runtime : False
Set to ``True`` to remove a runtime mask before attempting to enable
the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
enabling. This behavior is no longer the default.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
_check_for_unit_changes(name)
_check_unmask(name, unmask, unmask_runtime, root)
if name in _get_sysv_services(root):
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
service_exec = _get_service_exec()
if service_exec.endswith('/update-rc.d'):
cmd.extend([service_exec, '-f', name, 'defaults', '99'])
elif service_exec.endswith('/chkconfig'):
cmd.extend([service_exec, name, 'on'])
return __salt__['cmd.retcode'](cmd,
python_shell=False,
ignore_retcode=True) == 0
ret = __salt__['cmd.run_all'](
_systemctl_cmd('enable', name, systemd_scope=True, no_block=no_block,
root=root),
python_shell=False,
ignore_retcode=True)
if ret['retcode'] != 0:
# Instead of returning a bool, raise an exception so that we can
# include the error message in the return data. This helps give more
# information to the user in instances where the service is masked.
raise CommandExecutionError(_strip_scope(ret['stderr']))
return True | python | def enable(name, no_block=False, unmask=False, unmask_runtime=False,
root=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Enable the named service to start when the system boots
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
Set to ``True`` to remove an indefinite mask before attempting to
enable the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
enabling. This behavior is no longer the default.
unmask_runtime : False
Set to ``True`` to remove a runtime mask before attempting to enable
the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
enabling. This behavior is no longer the default.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
_check_for_unit_changes(name)
_check_unmask(name, unmask, unmask_runtime, root)
if name in _get_sysv_services(root):
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
service_exec = _get_service_exec()
if service_exec.endswith('/update-rc.d'):
cmd.extend([service_exec, '-f', name, 'defaults', '99'])
elif service_exec.endswith('/chkconfig'):
cmd.extend([service_exec, name, 'on'])
return __salt__['cmd.retcode'](cmd,
python_shell=False,
ignore_retcode=True) == 0
ret = __salt__['cmd.run_all'](
_systemctl_cmd('enable', name, systemd_scope=True, no_block=no_block,
root=root),
python_shell=False,
ignore_retcode=True)
if ret['retcode'] != 0:
# Instead of returning a bool, raise an exception so that we can
# include the error message in the return data. This helps give more
# information to the user in instances where the service is masked.
raise CommandExecutionError(_strip_scope(ret['stderr']))
return True | [
"def",
"enable",
"(",
"name",
",",
"no_block",
"=",
"False",
",",
"unmask",
"=",
"False",
",",
"unmask_runtime",
"=",
"False",
",",
"root",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"_check_for_unit_changes",
"(",
"... | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Enable the named service to start when the system boots
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
Set to ``True`` to remove an indefinite mask before attempting to
enable the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
enabling. This behavior is no longer the default.
unmask_runtime : False
Set to ``True`` to remove a runtime mask before attempting to enable
the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
enabling. This behavior is no longer the default.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name> | [
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"12",
"2016",
".",
"3",
".",
"3",
"2016",
".",
"11",
".",
"0",
"On",
"minions",
"running",
"systemd",
">",
"=",
"205",
"systemd",
"-",
"run",
"(",
"1",
")",
"_",
"is",
"now",
"used",
"to",
"i... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1112-L1184 | train |
saltstack/salt | salt/modules/systemd_service.py | disable | def disable(name, no_block=False, root=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Disable the named service to not start when the system boots
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
_check_for_unit_changes(name)
if name in _get_sysv_services(root):
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
service_exec = _get_service_exec()
if service_exec.endswith('/update-rc.d'):
cmd.extend([service_exec, '-f', name, 'remove'])
elif service_exec.endswith('/chkconfig'):
cmd.extend([service_exec, name, 'off'])
return __salt__['cmd.retcode'](cmd,
python_shell=False,
ignore_retcode=True) == 0
# Using cmd.run_all instead of cmd.retcode here to make unit tests easier
return __salt__['cmd.run_all'](
_systemctl_cmd('disable', name, systemd_scope=True, no_block=no_block,
root=root),
python_shell=False,
ignore_retcode=True)['retcode'] == 0 | python | def disable(name, no_block=False, root=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Disable the named service to not start when the system boots
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
_check_for_unit_changes(name)
if name in _get_sysv_services(root):
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
service_exec = _get_service_exec()
if service_exec.endswith('/update-rc.d'):
cmd.extend([service_exec, '-f', name, 'remove'])
elif service_exec.endswith('/chkconfig'):
cmd.extend([service_exec, name, 'off'])
return __salt__['cmd.retcode'](cmd,
python_shell=False,
ignore_retcode=True) == 0
# Using cmd.run_all instead of cmd.retcode here to make unit tests easier
return __salt__['cmd.run_all'](
_systemctl_cmd('disable', name, systemd_scope=True, no_block=no_block,
root=root),
python_shell=False,
ignore_retcode=True)['retcode'] == 0 | [
"def",
"disable",
"(",
"name",
",",
"no_block",
"=",
"False",
",",
"root",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"_check_for_unit_changes",
"(",
"name",
")",
"if",
"name",
"in",
"_get_sysv_services",
"(",
"root",
... | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Disable the named service to not start when the system boots
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name> | [
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"12",
"2016",
".",
"3",
".",
"3",
"2016",
".",
"11",
".",
"0",
"On",
"minions",
"running",
"systemd",
">",
"=",
"205",
"systemd",
"-",
"run",
"(",
"1",
")",
"_",
"is",
"now",
"used",
"to",
"i... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1189-L1237 | train |
saltstack/salt | salt/modules/systemd_service.py | enabled | def enabled(name, root=None, **kwargs): # pylint: disable=unused-argument
'''
Return if the named service is enabled to start on boot
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# Try 'systemctl is-enabled' first, then look for a symlink created by
# systemctl (older systemd releases did not support using is-enabled to
# check templated services), and lastly check for a sysvinit service.
if __salt__['cmd.retcode'](_systemctl_cmd('is-enabled', name, root=root),
python_shell=False,
ignore_retcode=True) == 0:
return True
elif '@' in name:
# On older systemd releases, templated services could not be checked
# with ``systemctl is-enabled``. As a fallback, look for the symlinks
# created by systemctl when enabling templated services.
local_config_path = _root(LOCAL_CONFIG_PATH, '/')
cmd = ['find', local_config_path, '-name', name,
'-type', 'l', '-print', '-quit']
# If the find command returns any matches, there will be output and the
# string will be non-empty.
if bool(__salt__['cmd.run'](cmd, python_shell=False)):
return True
elif name in _get_sysv_services(root):
return _sysv_enabled(name, root)
return False | python | def enabled(name, root=None, **kwargs): # pylint: disable=unused-argument
'''
Return if the named service is enabled to start on boot
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
# Try 'systemctl is-enabled' first, then look for a symlink created by
# systemctl (older systemd releases did not support using is-enabled to
# check templated services), and lastly check for a sysvinit service.
if __salt__['cmd.retcode'](_systemctl_cmd('is-enabled', name, root=root),
python_shell=False,
ignore_retcode=True) == 0:
return True
elif '@' in name:
# On older systemd releases, templated services could not be checked
# with ``systemctl is-enabled``. As a fallback, look for the symlinks
# created by systemctl when enabling templated services.
local_config_path = _root(LOCAL_CONFIG_PATH, '/')
cmd = ['find', local_config_path, '-name', name,
'-type', 'l', '-print', '-quit']
# If the find command returns any matches, there will be output and the
# string will be non-empty.
if bool(__salt__['cmd.run'](cmd, python_shell=False)):
return True
elif name in _get_sysv_services(root):
return _sysv_enabled(name, root)
return False | [
"def",
"enabled",
"(",
"name",
",",
"root",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"# Try 'systemctl is-enabled' first, then look for a symlink created by",
"# systemctl (older systemd releases did not support using is-enabled to",
"# c... | Return if the named service is enabled to start on boot
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name> | [
"Return",
"if",
"the",
"named",
"service",
"is",
"enabled",
"to",
"start",
"on",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1242-L1276 | train |
saltstack/salt | salt/modules/systemd_service.py | show | def show(name, root=None):
'''
.. versionadded:: 2014.7.0
Show properties of one or more units/jobs or the manager
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
salt '*' service.show <service name>
'''
ret = {}
out = __salt__['cmd.run'](_systemctl_cmd('show', name, root=root),
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
comps = line.split('=')
name = comps[0]
value = '='.join(comps[1:])
if value.startswith('{'):
value = value.replace('{', '').replace('}', '')
ret[name] = {}
for item in value.split(' ; '):
comps = item.split('=')
ret[name][comps[0].strip()] = comps[1].strip()
elif name in ('Before', 'After', 'Wants'):
ret[name] = value.split()
else:
ret[name] = value
return ret | python | def show(name, root=None):
'''
.. versionadded:: 2014.7.0
Show properties of one or more units/jobs or the manager
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
salt '*' service.show <service name>
'''
ret = {}
out = __salt__['cmd.run'](_systemctl_cmd('show', name, root=root),
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
comps = line.split('=')
name = comps[0]
value = '='.join(comps[1:])
if value.startswith('{'):
value = value.replace('{', '').replace('}', '')
ret[name] = {}
for item in value.split(' ; '):
comps = item.split('=')
ret[name][comps[0].strip()] = comps[1].strip()
elif name in ('Before', 'After', 'Wants'):
ret[name] = value.split()
else:
ret[name] = value
return ret | [
"def",
"show",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"_systemctl_cmd",
"(",
"'show'",
",",
"name",
",",
"root",
"=",
"root",
")",
",",
"python_shell",
"=",
"False"... | .. versionadded:: 2014.7.0
Show properties of one or more units/jobs or the manager
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
salt '*' service.show <service name> | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1295-L1326 | train |
saltstack/salt | salt/modules/systemd_service.py | execs | def execs(root=None):
'''
.. versionadded:: 2014.7.0
Return a list of all files specified as ``ExecStart`` for all services.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
salt '*' service.execs
'''
ret = {}
for service in get_all(root=root):
data = show(service, root=root)
if 'ExecStart' not in data:
continue
ret[service] = data['ExecStart']['path']
return ret | python | def execs(root=None):
'''
.. versionadded:: 2014.7.0
Return a list of all files specified as ``ExecStart`` for all services.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
salt '*' service.execs
'''
ret = {}
for service in get_all(root=root):
data = show(service, root=root)
if 'ExecStart' not in data:
continue
ret[service] = data['ExecStart']['path']
return ret | [
"def",
"execs",
"(",
"root",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"service",
"in",
"get_all",
"(",
"root",
"=",
"root",
")",
":",
"data",
"=",
"show",
"(",
"service",
",",
"root",
"=",
"root",
")",
"if",
"'ExecStart'",
"not",
"in",... | .. versionadded:: 2014.7.0
Return a list of all files specified as ``ExecStart`` for all services.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
salt '*' service.execs | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1329-L1348 | train |
saltstack/salt | salt/states/virt.py | keys | def keys(name, basepath='/etc/pki', **kwargs):
'''
Manage libvirt keys.
name
The name variable used to track the execution
basepath
Defaults to ``/etc/pki``, this is the root location used for libvirt
keys on the hypervisor
The following parameters are optional:
country
The country that the certificate should use. Defaults to US.
.. versionadded:: 2018.3.0
state
The state that the certificate should use. Defaults to Utah.
.. versionadded:: 2018.3.0
locality
The locality that the certificate should use.
Defaults to Salt Lake City.
.. versionadded:: 2018.3.0
organization
The organization that the certificate should use.
Defaults to Salted.
.. versionadded:: 2018.3.0
expiration_days
The number of days that the certificate should be valid for.
Defaults to 365 days (1 year)
.. versionadded:: 2018.3.0
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
# Grab all kwargs to make them available as pillar values
# rename them to something hopefully unique to avoid
# overriding anything existing
pillar_kwargs = {}
for key, value in six.iteritems(kwargs):
pillar_kwargs['ext_pillar_virt.{0}'.format(key)] = value
pillar = __salt__['pillar.ext']({'libvirt': '_'}, pillar_kwargs)
paths = {
'serverkey': os.path.join(basepath, 'libvirt',
'private', 'serverkey.pem'),
'servercert': os.path.join(basepath, 'libvirt',
'servercert.pem'),
'clientkey': os.path.join(basepath, 'libvirt',
'private', 'clientkey.pem'),
'clientcert': os.path.join(basepath, 'libvirt',
'clientcert.pem'),
'cacert': os.path.join(basepath, 'CA', 'cacert.pem')
}
for key in paths:
p_key = 'libvirt.{0}.pem'.format(key)
if p_key not in pillar:
continue
if not os.path.exists(os.path.dirname(paths[key])):
os.makedirs(os.path.dirname(paths[key]))
if os.path.isfile(paths[key]):
with salt.utils.files.fopen(paths[key], 'r') as fp_:
if salt.utils.stringutils.to_unicode(fp_.read()) != pillar[p_key]:
ret['changes'][key] = 'update'
else:
ret['changes'][key] = 'new'
if not ret['changes']:
ret['comment'] = 'All keys are correct'
elif __opts__['test']:
ret['result'] = None
ret['comment'] = 'Libvirt keys are set to be updated'
ret['changes'] = {}
else:
for key in ret['changes']:
with salt.utils.files.fopen(paths[key], 'w+') as fp_:
fp_.write(
salt.utils.stringutils.to_str(
pillar['libvirt.{0}.pem'.format(key)]
)
)
ret['comment'] = 'Updated libvirt certs and keys'
return ret | python | def keys(name, basepath='/etc/pki', **kwargs):
'''
Manage libvirt keys.
name
The name variable used to track the execution
basepath
Defaults to ``/etc/pki``, this is the root location used for libvirt
keys on the hypervisor
The following parameters are optional:
country
The country that the certificate should use. Defaults to US.
.. versionadded:: 2018.3.0
state
The state that the certificate should use. Defaults to Utah.
.. versionadded:: 2018.3.0
locality
The locality that the certificate should use.
Defaults to Salt Lake City.
.. versionadded:: 2018.3.0
organization
The organization that the certificate should use.
Defaults to Salted.
.. versionadded:: 2018.3.0
expiration_days
The number of days that the certificate should be valid for.
Defaults to 365 days (1 year)
.. versionadded:: 2018.3.0
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
# Grab all kwargs to make them available as pillar values
# rename them to something hopefully unique to avoid
# overriding anything existing
pillar_kwargs = {}
for key, value in six.iteritems(kwargs):
pillar_kwargs['ext_pillar_virt.{0}'.format(key)] = value
pillar = __salt__['pillar.ext']({'libvirt': '_'}, pillar_kwargs)
paths = {
'serverkey': os.path.join(basepath, 'libvirt',
'private', 'serverkey.pem'),
'servercert': os.path.join(basepath, 'libvirt',
'servercert.pem'),
'clientkey': os.path.join(basepath, 'libvirt',
'private', 'clientkey.pem'),
'clientcert': os.path.join(basepath, 'libvirt',
'clientcert.pem'),
'cacert': os.path.join(basepath, 'CA', 'cacert.pem')
}
for key in paths:
p_key = 'libvirt.{0}.pem'.format(key)
if p_key not in pillar:
continue
if not os.path.exists(os.path.dirname(paths[key])):
os.makedirs(os.path.dirname(paths[key]))
if os.path.isfile(paths[key]):
with salt.utils.files.fopen(paths[key], 'r') as fp_:
if salt.utils.stringutils.to_unicode(fp_.read()) != pillar[p_key]:
ret['changes'][key] = 'update'
else:
ret['changes'][key] = 'new'
if not ret['changes']:
ret['comment'] = 'All keys are correct'
elif __opts__['test']:
ret['result'] = None
ret['comment'] = 'Libvirt keys are set to be updated'
ret['changes'] = {}
else:
for key in ret['changes']:
with salt.utils.files.fopen(paths[key], 'w+') as fp_:
fp_.write(
salt.utils.stringutils.to_str(
pillar['libvirt.{0}.pem'.format(key)]
)
)
ret['comment'] = 'Updated libvirt certs and keys'
return ret | [
"def",
"keys",
"(",
"name",
",",
"basepath",
"=",
"'/etc/pki'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"# Grab all ... | Manage libvirt keys.
name
The name variable used to track the execution
basepath
Defaults to ``/etc/pki``, this is the root location used for libvirt
keys on the hypervisor
The following parameters are optional:
country
The country that the certificate should use. Defaults to US.
.. versionadded:: 2018.3.0
state
The state that the certificate should use. Defaults to Utah.
.. versionadded:: 2018.3.0
locality
The locality that the certificate should use.
Defaults to Salt Lake City.
.. versionadded:: 2018.3.0
organization
The organization that the certificate should use.
Defaults to Salted.
.. versionadded:: 2018.3.0
expiration_days
The number of days that the certificate should be valid for.
Defaults to 365 days (1 year)
.. versionadded:: 2018.3.0 | [
"Manage",
"libvirt",
"keys",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L51-L145 | train |
saltstack/salt | salt/states/virt.py | _virt_call | def _virt_call(domain, function, section, comment,
connection=None, username=None, password=None, **kwargs):
'''
Helper to call the virt functions. Wildcards supported.
:param domain:
:param function:
:param section:
:param comment:
:return:
'''
ret = {'name': domain, 'changes': {}, 'result': True, 'comment': ''}
targeted_domains = fnmatch.filter(__salt__['virt.list_domains'](), domain)
changed_domains = list()
ignored_domains = list()
for targeted_domain in targeted_domains:
try:
response = __salt__['virt.{0}'.format(function)](targeted_domain,
connection=connection,
username=username,
password=password,
**kwargs)
if isinstance(response, dict):
response = response['name']
changed_domains.append({'domain': targeted_domain, function: response})
except libvirt.libvirtError as err:
ignored_domains.append({'domain': targeted_domain, 'issue': six.text_type(err)})
if not changed_domains:
ret['result'] = False
ret['comment'] = 'No changes had happened'
if ignored_domains:
ret['changes'] = {'ignored': ignored_domains}
else:
ret['changes'] = {section: changed_domains}
ret['comment'] = comment
return ret | python | def _virt_call(domain, function, section, comment,
connection=None, username=None, password=None, **kwargs):
'''
Helper to call the virt functions. Wildcards supported.
:param domain:
:param function:
:param section:
:param comment:
:return:
'''
ret = {'name': domain, 'changes': {}, 'result': True, 'comment': ''}
targeted_domains = fnmatch.filter(__salt__['virt.list_domains'](), domain)
changed_domains = list()
ignored_domains = list()
for targeted_domain in targeted_domains:
try:
response = __salt__['virt.{0}'.format(function)](targeted_domain,
connection=connection,
username=username,
password=password,
**kwargs)
if isinstance(response, dict):
response = response['name']
changed_domains.append({'domain': targeted_domain, function: response})
except libvirt.libvirtError as err:
ignored_domains.append({'domain': targeted_domain, 'issue': six.text_type(err)})
if not changed_domains:
ret['result'] = False
ret['comment'] = 'No changes had happened'
if ignored_domains:
ret['changes'] = {'ignored': ignored_domains}
else:
ret['changes'] = {section: changed_domains}
ret['comment'] = comment
return ret | [
"def",
"_virt_call",
"(",
"domain",
",",
"function",
",",
"section",
",",
"comment",
",",
"connection",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"domai... | Helper to call the virt functions. Wildcards supported.
:param domain:
:param function:
:param section:
:param comment:
:return: | [
"Helper",
"to",
"call",
"the",
"virt",
"functions",
".",
"Wildcards",
"supported",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L148-L184 | train |
saltstack/salt | salt/states/virt.py | stopped | def stopped(name, connection=None, username=None, password=None):
'''
Stops a VM by shutting it down nicely.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.stopped
'''
return _virt_call(name, 'shutdown', 'stopped', "Machine has been shut down",
connection=connection, username=username, password=password) | python | def stopped(name, connection=None, username=None, password=None):
'''
Stops a VM by shutting it down nicely.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.stopped
'''
return _virt_call(name, 'shutdown', 'stopped', "Machine has been shut down",
connection=connection, username=username, password=password) | [
"def",
"stopped",
"(",
"name",
",",
"connection",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"return",
"_virt_call",
"(",
"name",
",",
"'shutdown'",
",",
"'stopped'",
",",
"\"Machine has been shut down\"",
",",
"connec... | Stops a VM by shutting it down nicely.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.stopped | [
"Stops",
"a",
"VM",
"by",
"shutting",
"it",
"down",
"nicely",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L187-L210 | train |
saltstack/salt | salt/states/virt.py | powered_off | def powered_off(name, connection=None, username=None, password=None):
'''
Stops a VM by power off.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.stopped
'''
return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off',
connection=connection, username=username, password=password) | python | def powered_off(name, connection=None, username=None, password=None):
'''
Stops a VM by power off.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.stopped
'''
return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off',
connection=connection, username=username, password=password) | [
"def",
"powered_off",
"(",
"name",
",",
"connection",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"return",
"_virt_call",
"(",
"name",
",",
"'stop'",
",",
"'unpowered'",
",",
"'Machine has been powered off'",
",",
"conn... | Stops a VM by power off.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.stopped | [
"Stops",
"a",
"VM",
"by",
"power",
"off",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L213-L236 | train |
saltstack/salt | salt/states/virt.py | running | def running(name,
cpu=None,
mem=None,
image=None,
vm_type=None,
disk_profile=None,
disks=None,
nic_profile=None,
interfaces=None,
graphics=None,
loader=None,
seed=True,
install=True,
pub_key=None,
priv_key=None,
update=False,
connection=None,
username=None,
password=None,
os_type=None,
arch=None):
'''
Starts an existing guest, or defines and starts a new VM with specified arguments.
.. versionadded:: 2016.3.0
:param name: name of the virtual machine to run
:param cpu: number of CPUs for the virtual machine to create
:param mem: amount of memory in MiB for the new virtual machine
:param image: disk image to use for the first disk of the new VM
.. deprecated:: 2019.2.0
:param vm_type: force virtual machine type for the new VM. The default value is taken from
the host capabilities. This could be useful for example to use ``'qemu'`` type instead
of the ``'kvm'`` one.
.. versionadded:: 2019.2.0
:param disk_profile:
Name of the disk profile to use for the new virtual machine
.. versionadded:: 2019.2.0
:param disks:
List of disk to create for the new virtual machine.
See the **Disk Definitions** section of the :py:func:`virt.init
<salt.modules.virt.init>` function for more details on the items on
this list.
.. versionadded:: 2019.2.0
:param nic_profile:
Name of the network interfaces profile to use for the new virtual machine
.. versionadded:: 2019.2.0
:param interfaces:
List of network interfaces to create for the new virtual machine.
See the **Network Interface Definitions** section of the
:py:func:`virt.init <salt.modules.virt.init>` function for more details
on the items on this list.
.. versionadded:: 2019.2.0
:param graphics:
Graphics device to create for the new virtual machine.
See the **Graphics Definition** section of the :py:func:`virt.init
<salt.modules.virt.init>` function for more details on this dictionary.
.. versionadded:: 2019.2.0
:param loader:
Firmware loader for the new virtual machine.
See the **Loader Definition** section of the :py:func:`virt.init
<salt.modules.virt.init>` function for more details on this dictionary.
.. versionadded:: 2019.2.0
:param saltenv:
Fileserver environment (Default: ``'base'``).
See :mod:`cp module for more details <salt.modules.cp>`
.. versionadded:: 2019.2.0
:param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided.
(Default: ``True``)
.. versionadded:: 2019.2.0
:param install: install salt minion if absent (Default: ``True``)
.. versionadded:: 2019.2.0
:param pub_key: public key to seed with (Default: ``None``)
.. versionadded:: 2019.2.0
:param priv_key: public key to seed with (Default: ``None``)
.. versionadded:: 2019.2.0
:param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``)
.. versionadded:: 2019.2.0
:param update: set to ``True`` to update a defined module. (Default: ``False``)
.. versionadded:: 2019.2.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param os_type:
type of virtualization as found in the ``//os/type`` element of the libvirt definition.
The default value is taken from the host capabilities, with a preference for ``hvm``.
Only used when creating a new virtual machine.
.. versionadded:: Neon
:param arch:
architecture of the virtual machine. The default value is taken from the host capabilities,
but ``x86_64`` is prefed over ``i686``. Only used when creating a new virtual machine.
.. versionadded:: Neon
.. rubric:: Example States
Make sure an already-defined virtual machine called ``domain_name`` is running:
.. code-block:: yaml
domain_name:
virt.running
Do the same, but define the virtual machine if needed:
.. code-block:: yaml
domain_name:
virt.running:
- cpu: 2
- mem: 2048
- disk_profile: prod
- disks:
- name: system
size: 8192
overlay_image: True
pool: default
image: /path/to/image.qcow2
- name: data
size: 16834
- nic_profile: prod
- interfaces:
- name: eth0
mac: 01:23:45:67:89:AB
- name: eth1
type: network
source: admin
- graphics:
- type: spice
listen:
- type: address
address: 192.168.0.125
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': '{0} is running'.format(name)
}
try:
try:
__salt__['virt.vm_state'](name)
if __salt__['virt.vm_state'](name) != 'running':
action_msg = 'started'
if update:
status = __salt__['virt.update'](name,
cpu=cpu,
mem=mem,
disk_profile=disk_profile,
disks=disks,
nic_profile=nic_profile,
interfaces=interfaces,
graphics=graphics,
live=False,
connection=connection,
username=username,
password=password)
if status['definition']:
action_msg = 'updated and started'
__salt__['virt.start'](name)
ret['changes'][name] = 'Domain {0}'.format(action_msg)
ret['comment'] = 'Domain {0} {1}'.format(name, action_msg)
else:
if update:
status = __salt__['virt.update'](name,
cpu=cpu,
mem=mem,
disk_profile=disk_profile,
disks=disks,
nic_profile=nic_profile,
interfaces=interfaces,
graphics=graphics,
connection=connection,
username=username,
password=password)
ret['changes'][name] = status
if status.get('errors', None):
ret['comment'] = 'Domain {0} updated, but some live update(s) failed'.format(name)
elif not status['definition']:
ret['comment'] = 'Domain {0} exists and is running'.format(name)
else:
ret['comment'] = 'Domain {0} updated, restart to fully apply the changes'.format(name)
else:
ret['comment'] = 'Domain {0} exists and is running'.format(name)
except CommandExecutionError:
if image:
salt.utils.versions.warn_until(
'Sodium',
'\'image\' parameter has been deprecated. Rather use the \'disks\' parameter '
'to override or define the image. \'image\' will be removed in {version}.'
)
__salt__['virt.init'](name,
cpu=cpu,
mem=mem,
os_type=os_type,
arch=arch,
image=image,
hypervisor=vm_type,
disk=disk_profile,
disks=disks,
nic=nic_profile,
interfaces=interfaces,
graphics=graphics,
loader=loader,
seed=seed,
install=install,
pub_key=pub_key,
priv_key=priv_key,
connection=connection,
username=username,
password=password)
ret['changes'][name] = 'Domain defined and started'
ret['comment'] = 'Domain {0} defined and started'.format(name)
except libvirt.libvirtError as err:
# Something bad happened when starting / updating the VM, report it
ret['comment'] = six.text_type(err)
ret['result'] = False
return ret | python | def running(name,
cpu=None,
mem=None,
image=None,
vm_type=None,
disk_profile=None,
disks=None,
nic_profile=None,
interfaces=None,
graphics=None,
loader=None,
seed=True,
install=True,
pub_key=None,
priv_key=None,
update=False,
connection=None,
username=None,
password=None,
os_type=None,
arch=None):
'''
Starts an existing guest, or defines and starts a new VM with specified arguments.
.. versionadded:: 2016.3.0
:param name: name of the virtual machine to run
:param cpu: number of CPUs for the virtual machine to create
:param mem: amount of memory in MiB for the new virtual machine
:param image: disk image to use for the first disk of the new VM
.. deprecated:: 2019.2.0
:param vm_type: force virtual machine type for the new VM. The default value is taken from
the host capabilities. This could be useful for example to use ``'qemu'`` type instead
of the ``'kvm'`` one.
.. versionadded:: 2019.2.0
:param disk_profile:
Name of the disk profile to use for the new virtual machine
.. versionadded:: 2019.2.0
:param disks:
List of disk to create for the new virtual machine.
See the **Disk Definitions** section of the :py:func:`virt.init
<salt.modules.virt.init>` function for more details on the items on
this list.
.. versionadded:: 2019.2.0
:param nic_profile:
Name of the network interfaces profile to use for the new virtual machine
.. versionadded:: 2019.2.0
:param interfaces:
List of network interfaces to create for the new virtual machine.
See the **Network Interface Definitions** section of the
:py:func:`virt.init <salt.modules.virt.init>` function for more details
on the items on this list.
.. versionadded:: 2019.2.0
:param graphics:
Graphics device to create for the new virtual machine.
See the **Graphics Definition** section of the :py:func:`virt.init
<salt.modules.virt.init>` function for more details on this dictionary.
.. versionadded:: 2019.2.0
:param loader:
Firmware loader for the new virtual machine.
See the **Loader Definition** section of the :py:func:`virt.init
<salt.modules.virt.init>` function for more details on this dictionary.
.. versionadded:: 2019.2.0
:param saltenv:
Fileserver environment (Default: ``'base'``).
See :mod:`cp module for more details <salt.modules.cp>`
.. versionadded:: 2019.2.0
:param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided.
(Default: ``True``)
.. versionadded:: 2019.2.0
:param install: install salt minion if absent (Default: ``True``)
.. versionadded:: 2019.2.0
:param pub_key: public key to seed with (Default: ``None``)
.. versionadded:: 2019.2.0
:param priv_key: public key to seed with (Default: ``None``)
.. versionadded:: 2019.2.0
:param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``)
.. versionadded:: 2019.2.0
:param update: set to ``True`` to update a defined module. (Default: ``False``)
.. versionadded:: 2019.2.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param os_type:
type of virtualization as found in the ``//os/type`` element of the libvirt definition.
The default value is taken from the host capabilities, with a preference for ``hvm``.
Only used when creating a new virtual machine.
.. versionadded:: Neon
:param arch:
architecture of the virtual machine. The default value is taken from the host capabilities,
but ``x86_64`` is prefed over ``i686``. Only used when creating a new virtual machine.
.. versionadded:: Neon
.. rubric:: Example States
Make sure an already-defined virtual machine called ``domain_name`` is running:
.. code-block:: yaml
domain_name:
virt.running
Do the same, but define the virtual machine if needed:
.. code-block:: yaml
domain_name:
virt.running:
- cpu: 2
- mem: 2048
- disk_profile: prod
- disks:
- name: system
size: 8192
overlay_image: True
pool: default
image: /path/to/image.qcow2
- name: data
size: 16834
- nic_profile: prod
- interfaces:
- name: eth0
mac: 01:23:45:67:89:AB
- name: eth1
type: network
source: admin
- graphics:
- type: spice
listen:
- type: address
address: 192.168.0.125
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': '{0} is running'.format(name)
}
try:
try:
__salt__['virt.vm_state'](name)
if __salt__['virt.vm_state'](name) != 'running':
action_msg = 'started'
if update:
status = __salt__['virt.update'](name,
cpu=cpu,
mem=mem,
disk_profile=disk_profile,
disks=disks,
nic_profile=nic_profile,
interfaces=interfaces,
graphics=graphics,
live=False,
connection=connection,
username=username,
password=password)
if status['definition']:
action_msg = 'updated and started'
__salt__['virt.start'](name)
ret['changes'][name] = 'Domain {0}'.format(action_msg)
ret['comment'] = 'Domain {0} {1}'.format(name, action_msg)
else:
if update:
status = __salt__['virt.update'](name,
cpu=cpu,
mem=mem,
disk_profile=disk_profile,
disks=disks,
nic_profile=nic_profile,
interfaces=interfaces,
graphics=graphics,
connection=connection,
username=username,
password=password)
ret['changes'][name] = status
if status.get('errors', None):
ret['comment'] = 'Domain {0} updated, but some live update(s) failed'.format(name)
elif not status['definition']:
ret['comment'] = 'Domain {0} exists and is running'.format(name)
else:
ret['comment'] = 'Domain {0} updated, restart to fully apply the changes'.format(name)
else:
ret['comment'] = 'Domain {0} exists and is running'.format(name)
except CommandExecutionError:
if image:
salt.utils.versions.warn_until(
'Sodium',
'\'image\' parameter has been deprecated. Rather use the \'disks\' parameter '
'to override or define the image. \'image\' will be removed in {version}.'
)
__salt__['virt.init'](name,
cpu=cpu,
mem=mem,
os_type=os_type,
arch=arch,
image=image,
hypervisor=vm_type,
disk=disk_profile,
disks=disks,
nic=nic_profile,
interfaces=interfaces,
graphics=graphics,
loader=loader,
seed=seed,
install=install,
pub_key=pub_key,
priv_key=priv_key,
connection=connection,
username=username,
password=password)
ret['changes'][name] = 'Domain defined and started'
ret['comment'] = 'Domain {0} defined and started'.format(name)
except libvirt.libvirtError as err:
# Something bad happened when starting / updating the VM, report it
ret['comment'] = six.text_type(err)
ret['result'] = False
return ret | [
"def",
"running",
"(",
"name",
",",
"cpu",
"=",
"None",
",",
"mem",
"=",
"None",
",",
"image",
"=",
"None",
",",
"vm_type",
"=",
"None",
",",
"disk_profile",
"=",
"None",
",",
"disks",
"=",
"None",
",",
"nic_profile",
"=",
"None",
",",
"interfaces",
... | Starts an existing guest, or defines and starts a new VM with specified arguments.
.. versionadded:: 2016.3.0
:param name: name of the virtual machine to run
:param cpu: number of CPUs for the virtual machine to create
:param mem: amount of memory in MiB for the new virtual machine
:param image: disk image to use for the first disk of the new VM
.. deprecated:: 2019.2.0
:param vm_type: force virtual machine type for the new VM. The default value is taken from
the host capabilities. This could be useful for example to use ``'qemu'`` type instead
of the ``'kvm'`` one.
.. versionadded:: 2019.2.0
:param disk_profile:
Name of the disk profile to use for the new virtual machine
.. versionadded:: 2019.2.0
:param disks:
List of disk to create for the new virtual machine.
See the **Disk Definitions** section of the :py:func:`virt.init
<salt.modules.virt.init>` function for more details on the items on
this list.
.. versionadded:: 2019.2.0
:param nic_profile:
Name of the network interfaces profile to use for the new virtual machine
.. versionadded:: 2019.2.0
:param interfaces:
List of network interfaces to create for the new virtual machine.
See the **Network Interface Definitions** section of the
:py:func:`virt.init <salt.modules.virt.init>` function for more details
on the items on this list.
.. versionadded:: 2019.2.0
:param graphics:
Graphics device to create for the new virtual machine.
See the **Graphics Definition** section of the :py:func:`virt.init
<salt.modules.virt.init>` function for more details on this dictionary.
.. versionadded:: 2019.2.0
:param loader:
Firmware loader for the new virtual machine.
See the **Loader Definition** section of the :py:func:`virt.init
<salt.modules.virt.init>` function for more details on this dictionary.
.. versionadded:: 2019.2.0
:param saltenv:
Fileserver environment (Default: ``'base'``).
See :mod:`cp module for more details <salt.modules.cp>`
.. versionadded:: 2019.2.0
:param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided.
(Default: ``True``)
.. versionadded:: 2019.2.0
:param install: install salt minion if absent (Default: ``True``)
.. versionadded:: 2019.2.0
:param pub_key: public key to seed with (Default: ``None``)
.. versionadded:: 2019.2.0
:param priv_key: public key to seed with (Default: ``None``)
.. versionadded:: 2019.2.0
:param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``)
.. versionadded:: 2019.2.0
:param update: set to ``True`` to update a defined module. (Default: ``False``)
.. versionadded:: 2019.2.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param os_type:
type of virtualization as found in the ``//os/type`` element of the libvirt definition.
The default value is taken from the host capabilities, with a preference for ``hvm``.
Only used when creating a new virtual machine.
.. versionadded:: Neon
:param arch:
architecture of the virtual machine. The default value is taken from the host capabilities,
but ``x86_64`` is prefed over ``i686``. Only used when creating a new virtual machine.
.. versionadded:: Neon
.. rubric:: Example States
Make sure an already-defined virtual machine called ``domain_name`` is running:
.. code-block:: yaml
domain_name:
virt.running
Do the same, but define the virtual machine if needed:
.. code-block:: yaml
domain_name:
virt.running:
- cpu: 2
- mem: 2048
- disk_profile: prod
- disks:
- name: system
size: 8192
overlay_image: True
pool: default
image: /path/to/image.qcow2
- name: data
size: 16834
- nic_profile: prod
- interfaces:
- name: eth0
mac: 01:23:45:67:89:AB
- name: eth1
type: network
source: admin
- graphics:
- type: spice
listen:
- type: address
address: 192.168.0.125 | [
"Starts",
"an",
"existing",
"guest",
"or",
"defines",
"and",
"starts",
"a",
"new",
"VM",
"with",
"specified",
"arguments",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L239-L481 | train |
saltstack/salt | salt/states/virt.py | snapshot | def snapshot(name, suffix=None, connection=None, username=None, password=None):
'''
Takes a snapshot of a particular VM or by a UNIX-style wildcard.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.snapshot:
- suffix: periodic
domain*:
virt.snapshot:
- suffix: periodic
'''
return _virt_call(name, 'snapshot', 'saved', 'Snapshot has been taken', suffix=suffix,
connection=connection, username=username, password=password) | python | def snapshot(name, suffix=None, connection=None, username=None, password=None):
'''
Takes a snapshot of a particular VM or by a UNIX-style wildcard.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.snapshot:
- suffix: periodic
domain*:
virt.snapshot:
- suffix: periodic
'''
return _virt_call(name, 'snapshot', 'saved', 'Snapshot has been taken', suffix=suffix,
connection=connection, username=username, password=password) | [
"def",
"snapshot",
"(",
"name",
",",
"suffix",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"return",
"_virt_call",
"(",
"name",
",",
"'snapshot'",
",",
"'saved'",
",",
"'Snapshot has ... | Takes a snapshot of a particular VM or by a UNIX-style wildcard.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.snapshot:
- suffix: periodic
domain*:
virt.snapshot:
- suffix: periodic | [
"Takes",
"a",
"snapshot",
"of",
"a",
"particular",
"VM",
"or",
"by",
"a",
"UNIX",
"-",
"style",
"wildcard",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L484-L512 | train |
saltstack/salt | salt/states/virt.py | rebooted | def rebooted(name, connection=None, username=None, password=None):
'''
Reboots VMs
.. versionadded:: 2016.3.0
:param name:
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
'''
return _virt_call(name, 'reboot', 'rebooted', "Machine has been rebooted",
connection=connection, username=username, password=password) | python | def rebooted(name, connection=None, username=None, password=None):
'''
Reboots VMs
.. versionadded:: 2016.3.0
:param name:
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
'''
return _virt_call(name, 'reboot', 'rebooted', "Machine has been rebooted",
connection=connection, username=username, password=password) | [
"def",
"rebooted",
"(",
"name",
",",
"connection",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"return",
"_virt_call",
"(",
"name",
",",
"'reboot'",
",",
"'rebooted'",
",",
"\"Machine has been rebooted\"",
",",
"connect... | Reboots VMs
.. versionadded:: 2016.3.0
:param name:
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0 | [
"Reboots",
"VMs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L516-L536 | train |
saltstack/salt | salt/states/virt.py | reverted | def reverted(name, snapshot=None, cleanup=False): # pylint: disable=redefined-outer-name
'''
.. deprecated:: 2016.3.0
Reverts to the particular snapshot.
.. versionadded:: 2016.3.0
.. code-block:: yaml
domain_name:
virt.reverted:
- cleanup: True
domain_name_1:
virt.reverted:
- snapshot: snapshot_name
- cleanup: False
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
try:
domains = fnmatch.filter(__salt__['virt.list_domains'](), name)
if not domains:
ret['comment'] = 'No domains found for criteria "{0}"'.format(name)
else:
ignored_domains = list()
if len(domains) > 1:
ret['changes'] = {'reverted': list()}
for domain in domains:
result = {}
try:
result = __salt__['virt.revert_snapshot'](domain, snapshot=snapshot, cleanup=cleanup)
result = {'domain': domain, 'current': result['reverted'], 'deleted': result['deleted']}
except CommandExecutionError as err:
if len(domains) > 1:
ignored_domains.append({'domain': domain, 'issue': six.text_type(err)})
if len(domains) > 1:
if result:
ret['changes']['reverted'].append(result)
else:
ret['changes'] = result
break
ret['result'] = len(domains) != len(ignored_domains)
if ret['result']:
ret['comment'] = 'Domain{0} has been reverted'.format(len(domains) > 1 and "s" or "")
if ignored_domains:
ret['changes']['ignored'] = ignored_domains
if not ret['changes']['reverted']:
ret['changes'].pop('reverted')
except libvirt.libvirtError as err:
ret['comment'] = six.text_type(err)
except CommandExecutionError as err:
ret['comment'] = six.text_type(err)
return ret | python | def reverted(name, snapshot=None, cleanup=False): # pylint: disable=redefined-outer-name
'''
.. deprecated:: 2016.3.0
Reverts to the particular snapshot.
.. versionadded:: 2016.3.0
.. code-block:: yaml
domain_name:
virt.reverted:
- cleanup: True
domain_name_1:
virt.reverted:
- snapshot: snapshot_name
- cleanup: False
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
try:
domains = fnmatch.filter(__salt__['virt.list_domains'](), name)
if not domains:
ret['comment'] = 'No domains found for criteria "{0}"'.format(name)
else:
ignored_domains = list()
if len(domains) > 1:
ret['changes'] = {'reverted': list()}
for domain in domains:
result = {}
try:
result = __salt__['virt.revert_snapshot'](domain, snapshot=snapshot, cleanup=cleanup)
result = {'domain': domain, 'current': result['reverted'], 'deleted': result['deleted']}
except CommandExecutionError as err:
if len(domains) > 1:
ignored_domains.append({'domain': domain, 'issue': six.text_type(err)})
if len(domains) > 1:
if result:
ret['changes']['reverted'].append(result)
else:
ret['changes'] = result
break
ret['result'] = len(domains) != len(ignored_domains)
if ret['result']:
ret['comment'] = 'Domain{0} has been reverted'.format(len(domains) > 1 and "s" or "")
if ignored_domains:
ret['changes']['ignored'] = ignored_domains
if not ret['changes']['reverted']:
ret['changes'].pop('reverted')
except libvirt.libvirtError as err:
ret['comment'] = six.text_type(err)
except CommandExecutionError as err:
ret['comment'] = six.text_type(err)
return ret | [
"def",
"reverted",
"(",
"name",
",",
"snapshot",
"=",
"None",
",",
"cleanup",
"=",
"False",
")",
":",
"# pylint: disable=redefined-outer-name",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"... | .. deprecated:: 2016.3.0
Reverts to the particular snapshot.
.. versionadded:: 2016.3.0
.. code-block:: yaml
domain_name:
virt.reverted:
- cleanup: True
domain_name_1:
virt.reverted:
- snapshot: snapshot_name
- cleanup: False | [
"..",
"deprecated",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L580-L636 | train |
saltstack/salt | salt/states/virt.py | network_running | def network_running(name,
bridge,
forward,
vport=None,
tag=None,
autostart=True,
connection=None,
username=None,
password=None):
'''
Defines and starts a new network with specified arguments.
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.network_define
.. code-block:: yaml
network_name:
virt.network_define:
- bridge: main
- forward: bridge
- vport: openvswitch
- tag: 180
- autostart: True
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''
}
try:
info = __salt__['virt.network_info'](name, connection=connection, username=username, password=password)
if info:
if info['active']:
ret['comment'] = 'Network {0} exists and is running'.format(name)
else:
__salt__['virt.network_start'](name, connection=connection, username=username, password=password)
ret['changes'][name] = 'Network started'
ret['comment'] = 'Network {0} started'.format(name)
else:
__salt__['virt.network_define'](name,
bridge,
forward,
vport,
tag=tag,
autostart=autostart,
start=True,
connection=connection,
username=username,
password=password)
ret['changes'][name] = 'Network defined and started'
ret['comment'] = 'Network {0} defined and started'.format(name)
except libvirt.libvirtError as err:
ret['result'] = False
ret['comment'] = err.get_error_message()
return ret | python | def network_running(name,
bridge,
forward,
vport=None,
tag=None,
autostart=True,
connection=None,
username=None,
password=None):
'''
Defines and starts a new network with specified arguments.
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.network_define
.. code-block:: yaml
network_name:
virt.network_define:
- bridge: main
- forward: bridge
- vport: openvswitch
- tag: 180
- autostart: True
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''
}
try:
info = __salt__['virt.network_info'](name, connection=connection, username=username, password=password)
if info:
if info['active']:
ret['comment'] = 'Network {0} exists and is running'.format(name)
else:
__salt__['virt.network_start'](name, connection=connection, username=username, password=password)
ret['changes'][name] = 'Network started'
ret['comment'] = 'Network {0} started'.format(name)
else:
__salt__['virt.network_define'](name,
bridge,
forward,
vport,
tag=tag,
autostart=autostart,
start=True,
connection=connection,
username=username,
password=password)
ret['changes'][name] = 'Network defined and started'
ret['comment'] = 'Network {0} defined and started'.format(name)
except libvirt.libvirtError as err:
ret['result'] = False
ret['comment'] = err.get_error_message()
return ret | [
"def",
"network_running",
"(",
"name",
",",
"bridge",
",",
"forward",
",",
"vport",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"autostart",
"=",
"True",
",",
"connection",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
... | Defines and starts a new network with specified arguments.
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: yaml
domain_name:
virt.network_define
.. code-block:: yaml
network_name:
virt.network_define:
- bridge: main
- forward: bridge
- vport: openvswitch
- tag: 180
- autostart: True | [
"Defines",
"and",
"starts",
"a",
"new",
"network",
"with",
"specified",
"arguments",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L639-L709 | train |
saltstack/salt | salt/states/virt.py | pool_running | def pool_running(name,
ptype=None,
target=None,
permissions=None,
source=None,
transient=False,
autostart=True,
connection=None,
username=None,
password=None):
'''
Defines and starts a new pool with specified arguments.
.. versionadded:: 2019.2.0
:param ptype: libvirt pool type
:param target: full path to the target device or folder. (Default: ``None``)
:param permissions: target permissions. See the **Permissions definition**
section of the :py:func:`virt.pool_define
<salt.module.virt.pool_define>` documentation for more details on this
structure.
:param source:
dictionary containing keys matching the ``source_*`` parameters in function
:py:func:`virt.pool_define <salt.modules.virt.pool_define>`.
:param transient:
when set to ``True``, the pool will be automatically undefined after
being stopped. (Default: ``False``)
:param autostart:
Whether to start the pool when booting the host. (Default: ``True``)
:param start:
When ``True``, define and start the pool, otherwise the pool will be
left stopped.
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect with, overriding defaults
.. code-block:: yaml
pool_name:
virt.pool_define
.. code-block:: yaml
pool_name:
virt.pool_define:
- ptype: netfs
- target: /mnt/cifs
- permissions:
- mode: 0770
- owner: 1000
- group: 100
- source:
- dir: samba_share
- hosts:
one.example.com
two.example.com
- format: cifs
- autostart: True
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''
}
try:
info = __salt__['virt.pool_info'](name, connection=connection, username=username, password=password)
if info:
if info['state'] == 'running':
ret['comment'] = 'Pool {0} exists and is running'.format(name)
else:
__salt__['virt.pool_start'](name, connection=connection, username=username, password=password)
ret['changes'][name] = 'Pool started'
ret['comment'] = 'Pool {0} started'.format(name)
else:
__salt__['virt.pool_define'](name,
ptype=ptype,
target=target,
permissions=permissions,
source_devices=(source or {}).get('devices', None),
source_dir=(source or {}).get('dir', None),
source_adapter=(source or {}).get('adapter', None),
source_hosts=(source or {}).get('hosts', None),
source_auth=(source or {}).get('auth', None),
source_name=(source or {}).get('name', None),
source_format=(source or {}).get('format', None),
transient=transient,
start=True,
connection=connection,
username=username,
password=password)
if autostart:
__salt__['virt.pool_set_autostart'](name,
state='on' if autostart else 'off',
connection=connection,
username=username,
password=password)
__salt__['virt.pool_build'](name,
connection=connection,
username=username,
password=password)
__salt__['virt.pool_start'](name,
connection=connection,
username=username,
password=password)
ret['changes'][name] = 'Pool defined and started'
ret['comment'] = 'Pool {0} defined and started'.format(name)
except libvirt.libvirtError as err:
ret['comment'] = err.get_error_message()
ret['result'] = False
return ret | python | def pool_running(name,
ptype=None,
target=None,
permissions=None,
source=None,
transient=False,
autostart=True,
connection=None,
username=None,
password=None):
'''
Defines and starts a new pool with specified arguments.
.. versionadded:: 2019.2.0
:param ptype: libvirt pool type
:param target: full path to the target device or folder. (Default: ``None``)
:param permissions: target permissions. See the **Permissions definition**
section of the :py:func:`virt.pool_define
<salt.module.virt.pool_define>` documentation for more details on this
structure.
:param source:
dictionary containing keys matching the ``source_*`` parameters in function
:py:func:`virt.pool_define <salt.modules.virt.pool_define>`.
:param transient:
when set to ``True``, the pool will be automatically undefined after
being stopped. (Default: ``False``)
:param autostart:
Whether to start the pool when booting the host. (Default: ``True``)
:param start:
When ``True``, define and start the pool, otherwise the pool will be
left stopped.
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect with, overriding defaults
.. code-block:: yaml
pool_name:
virt.pool_define
.. code-block:: yaml
pool_name:
virt.pool_define:
- ptype: netfs
- target: /mnt/cifs
- permissions:
- mode: 0770
- owner: 1000
- group: 100
- source:
- dir: samba_share
- hosts:
one.example.com
two.example.com
- format: cifs
- autostart: True
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''
}
try:
info = __salt__['virt.pool_info'](name, connection=connection, username=username, password=password)
if info:
if info['state'] == 'running':
ret['comment'] = 'Pool {0} exists and is running'.format(name)
else:
__salt__['virt.pool_start'](name, connection=connection, username=username, password=password)
ret['changes'][name] = 'Pool started'
ret['comment'] = 'Pool {0} started'.format(name)
else:
__salt__['virt.pool_define'](name,
ptype=ptype,
target=target,
permissions=permissions,
source_devices=(source or {}).get('devices', None),
source_dir=(source or {}).get('dir', None),
source_adapter=(source or {}).get('adapter', None),
source_hosts=(source or {}).get('hosts', None),
source_auth=(source or {}).get('auth', None),
source_name=(source or {}).get('name', None),
source_format=(source or {}).get('format', None),
transient=transient,
start=True,
connection=connection,
username=username,
password=password)
if autostart:
__salt__['virt.pool_set_autostart'](name,
state='on' if autostart else 'off',
connection=connection,
username=username,
password=password)
__salt__['virt.pool_build'](name,
connection=connection,
username=username,
password=password)
__salt__['virt.pool_start'](name,
connection=connection,
username=username,
password=password)
ret['changes'][name] = 'Pool defined and started'
ret['comment'] = 'Pool {0} defined and started'.format(name)
except libvirt.libvirtError as err:
ret['comment'] = err.get_error_message()
ret['result'] = False
return ret | [
"def",
"pool_running",
"(",
"name",
",",
"ptype",
"=",
"None",
",",
"target",
"=",
"None",
",",
"permissions",
"=",
"None",
",",
"source",
"=",
"None",
",",
"transient",
"=",
"False",
",",
"autostart",
"=",
"True",
",",
"connection",
"=",
"None",
",",
... | Defines and starts a new pool with specified arguments.
.. versionadded:: 2019.2.0
:param ptype: libvirt pool type
:param target: full path to the target device or folder. (Default: ``None``)
:param permissions: target permissions. See the **Permissions definition**
section of the :py:func:`virt.pool_define
<salt.module.virt.pool_define>` documentation for more details on this
structure.
:param source:
dictionary containing keys matching the ``source_*`` parameters in function
:py:func:`virt.pool_define <salt.modules.virt.pool_define>`.
:param transient:
when set to ``True``, the pool will be automatically undefined after
being stopped. (Default: ``False``)
:param autostart:
Whether to start the pool when booting the host. (Default: ``True``)
:param start:
When ``True``, define and start the pool, otherwise the pool will be
left stopped.
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect with, overriding defaults
.. code-block:: yaml
pool_name:
virt.pool_define
.. code-block:: yaml
pool_name:
virt.pool_define:
- ptype: netfs
- target: /mnt/cifs
- permissions:
- mode: 0770
- owner: 1000
- group: 100
- source:
- dir: samba_share
- hosts:
one.example.com
two.example.com
- format: cifs
- autostart: True | [
"Defines",
"and",
"starts",
"a",
"new",
"pool",
"with",
"specified",
"arguments",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L712-L826 | train |
saltstack/salt | salt/modules/runit.py | status | def status(name, sig=None):
'''
Return ``True`` if service is running
name
the service's name
sig
signature to identify with ps
CLI Example:
.. code-block:: bash
salt '*' runit.status <service name>
'''
if sig:
# usual way to do by others (debian_service, netbsdservice).
# XXX probably does not work here (check 'runsv sshd' instead of 'sshd' ?)
return bool(__salt__['status.pid'](sig))
svc_path = _service_path(name)
if not os.path.exists(svc_path):
# service does not exist
return False
# sv return code is not relevant to get a service status.
# Check its output instead.
cmd = 'sv status {0}'.format(svc_path)
try:
out = __salt__['cmd.run_stdout'](cmd)
return out.startswith('run: ')
except Exception:
# sv (as a command) returned an error
return False | python | def status(name, sig=None):
'''
Return ``True`` if service is running
name
the service's name
sig
signature to identify with ps
CLI Example:
.. code-block:: bash
salt '*' runit.status <service name>
'''
if sig:
# usual way to do by others (debian_service, netbsdservice).
# XXX probably does not work here (check 'runsv sshd' instead of 'sshd' ?)
return bool(__salt__['status.pid'](sig))
svc_path = _service_path(name)
if not os.path.exists(svc_path):
# service does not exist
return False
# sv return code is not relevant to get a service status.
# Check its output instead.
cmd = 'sv status {0}'.format(svc_path)
try:
out = __salt__['cmd.run_stdout'](cmd)
return out.startswith('run: ')
except Exception:
# sv (as a command) returned an error
return False | [
"def",
"status",
"(",
"name",
",",
"sig",
"=",
"None",
")",
":",
"if",
"sig",
":",
"# usual way to do by others (debian_service, netbsdservice).",
"# XXX probably does not work here (check 'runsv sshd' instead of 'sshd' ?)",
"return",
"bool",
"(",
"__salt__",
"[",
"'status.pi... | Return ``True`` if service is running
name
the service's name
sig
signature to identify with ps
CLI Example:
.. code-block:: bash
salt '*' runit.status <service name> | [
"Return",
"True",
"if",
"service",
"is",
"running"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L206-L240 | train |
saltstack/salt | salt/modules/runit.py | _is_svc | def _is_svc(svc_path):
'''
Return ``True`` if directory <svc_path> is really a service:
file <svc_path>/run exists and is executable
svc_path
the (absolute) directory to check for compatibility
'''
run_file = os.path.join(svc_path, 'run')
if (os.path.exists(svc_path)
and os.path.exists(run_file)
and os.access(run_file, os.X_OK)):
return True
return False | python | def _is_svc(svc_path):
'''
Return ``True`` if directory <svc_path> is really a service:
file <svc_path>/run exists and is executable
svc_path
the (absolute) directory to check for compatibility
'''
run_file = os.path.join(svc_path, 'run')
if (os.path.exists(svc_path)
and os.path.exists(run_file)
and os.access(run_file, os.X_OK)):
return True
return False | [
"def",
"_is_svc",
"(",
"svc_path",
")",
":",
"run_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"svc_path",
",",
"'run'",
")",
"if",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"svc_path",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"ru... | Return ``True`` if directory <svc_path> is really a service:
file <svc_path>/run exists and is executable
svc_path
the (absolute) directory to check for compatibility | [
"Return",
"True",
"if",
"directory",
"<svc_path",
">",
"is",
"really",
"a",
"service",
":",
"file",
"<svc_path",
">",
"/",
"run",
"exists",
"and",
"is",
"executable"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L243-L256 | train |
saltstack/salt | salt/modules/runit.py | status_autostart | def status_autostart(name):
'''
Return ``True`` if service <name> is autostarted by sv
(file $service_folder/down does not exist)
NB: return ``False`` if the service is not enabled.
name
the service's name
CLI Example:
.. code-block:: bash
salt '*' runit.status_autostart <service name>
'''
return not os.path.exists(os.path.join(_service_path(name), 'down')) | python | def status_autostart(name):
'''
Return ``True`` if service <name> is autostarted by sv
(file $service_folder/down does not exist)
NB: return ``False`` if the service is not enabled.
name
the service's name
CLI Example:
.. code-block:: bash
salt '*' runit.status_autostart <service name>
'''
return not os.path.exists(os.path.join(_service_path(name), 'down')) | [
"def",
"status_autostart",
"(",
"name",
")",
":",
"return",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"_service_path",
"(",
"name",
")",
",",
"'down'",
")",
")"
] | Return ``True`` if service <name> is autostarted by sv
(file $service_folder/down does not exist)
NB: return ``False`` if the service is not enabled.
name
the service's name
CLI Example:
.. code-block:: bash
salt '*' runit.status_autostart <service name> | [
"Return",
"True",
"if",
"service",
"<name",
">",
"is",
"autostarted",
"by",
"sv",
"(",
"file",
"$service_folder",
"/",
"down",
"does",
"not",
"exist",
")",
"NB",
":",
"return",
"False",
"if",
"the",
"service",
"is",
"not",
"enabled",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L259-L274 | train |
saltstack/salt | salt/modules/runit.py | get_svc_broken_path | def get_svc_broken_path(name='*'):
'''
Return list of broken path(s) in SERVICE_DIR that match ``name``
A path is broken if it is a broken symlink or can not be a runit service
name
a glob for service name. default is '*'
CLI Example:
.. code-block:: bash
salt '*' runit.get_svc_broken_path <service name>
'''
if not SERVICE_DIR:
raise CommandExecutionError('Could not find service directory.')
ret = set()
for el in glob.glob(os.path.join(SERVICE_DIR, name)):
if not _is_svc(el):
ret.add(el)
return sorted(ret) | python | def get_svc_broken_path(name='*'):
'''
Return list of broken path(s) in SERVICE_DIR that match ``name``
A path is broken if it is a broken symlink or can not be a runit service
name
a glob for service name. default is '*'
CLI Example:
.. code-block:: bash
salt '*' runit.get_svc_broken_path <service name>
'''
if not SERVICE_DIR:
raise CommandExecutionError('Could not find service directory.')
ret = set()
for el in glob.glob(os.path.join(SERVICE_DIR, name)):
if not _is_svc(el):
ret.add(el)
return sorted(ret) | [
"def",
"get_svc_broken_path",
"(",
"name",
"=",
"'*'",
")",
":",
"if",
"not",
"SERVICE_DIR",
":",
"raise",
"CommandExecutionError",
"(",
"'Could not find service directory.'",
")",
"ret",
"=",
"set",
"(",
")",
"for",
"el",
"in",
"glob",
".",
"glob",
"(",
"os... | Return list of broken path(s) in SERVICE_DIR that match ``name``
A path is broken if it is a broken symlink or can not be a runit service
name
a glob for service name. default is '*'
CLI Example:
.. code-block:: bash
salt '*' runit.get_svc_broken_path <service name> | [
"Return",
"list",
"of",
"broken",
"path",
"(",
"s",
")",
"in",
"SERVICE_DIR",
"that",
"match",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L277-L300 | train |
saltstack/salt | salt/modules/runit.py | add_svc_avail_path | def add_svc_avail_path(path):
'''
Add a path that may contain available services.
Return ``True`` if added (or already present), ``False`` on error.
path
directory to add to AVAIL_SVR_DIRS
'''
if os.path.exists(path):
if path not in AVAIL_SVR_DIRS:
AVAIL_SVR_DIRS.append(path)
return True
return False | python | def add_svc_avail_path(path):
'''
Add a path that may contain available services.
Return ``True`` if added (or already present), ``False`` on error.
path
directory to add to AVAIL_SVR_DIRS
'''
if os.path.exists(path):
if path not in AVAIL_SVR_DIRS:
AVAIL_SVR_DIRS.append(path)
return True
return False | [
"def",
"add_svc_avail_path",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"path",
"not",
"in",
"AVAIL_SVR_DIRS",
":",
"AVAIL_SVR_DIRS",
".",
"append",
"(",
"path",
")",
"return",
"True",
"return",
"False"
] | Add a path that may contain available services.
Return ``True`` if added (or already present), ``False`` on error.
path
directory to add to AVAIL_SVR_DIRS | [
"Add",
"a",
"path",
"that",
"may",
"contain",
"available",
"services",
".",
"Return",
"True",
"if",
"added",
"(",
"or",
"already",
"present",
")",
"False",
"on",
"error",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L310-L322 | train |
saltstack/salt | salt/modules/runit.py | _get_svc_path | def _get_svc_path(name='*', status=None):
'''
Return a list of paths to services with ``name`` that have the specified ``status``
name
a glob for service name. default is '*'
status
None : all services (no filter, default choice)
'DISABLED' : available service(s) that is not enabled
'ENABLED' : enabled service (whether started on boot or not)
'''
# This is the core routine to work with services, called by many
# other functions of this module.
#
# The name of a service is the "apparent" folder's name that contains its
# "run" script. If its "folder" is a symlink, the service is an "alias" of
# the targeted service.
if not SERVICE_DIR:
raise CommandExecutionError('Could not find service directory.')
# path list of enabled services as /AVAIL_SVR_DIRS/$service,
# taking care of any service aliases (do not use os.path.realpath()).
ena = set()
for el in glob.glob(os.path.join(SERVICE_DIR, name)):
if _is_svc(el):
ena.add(os.readlink(el))
log.trace('found enabled service path: %s', el)
if status == 'ENABLED':
return sorted(ena)
# path list of available services as /AVAIL_SVR_DIRS/$service
ava = set()
for d in AVAIL_SVR_DIRS:
for el in glob.glob(os.path.join(d, name)):
if _is_svc(el):
ava.add(el)
log.trace('found available service path: %s', el)
if status == 'DISABLED':
# service available but not enabled
ret = ava.difference(ena)
else:
# default: return available services
ret = ava.union(ena)
return sorted(ret) | python | def _get_svc_path(name='*', status=None):
'''
Return a list of paths to services with ``name`` that have the specified ``status``
name
a glob for service name. default is '*'
status
None : all services (no filter, default choice)
'DISABLED' : available service(s) that is not enabled
'ENABLED' : enabled service (whether started on boot or not)
'''
# This is the core routine to work with services, called by many
# other functions of this module.
#
# The name of a service is the "apparent" folder's name that contains its
# "run" script. If its "folder" is a symlink, the service is an "alias" of
# the targeted service.
if not SERVICE_DIR:
raise CommandExecutionError('Could not find service directory.')
# path list of enabled services as /AVAIL_SVR_DIRS/$service,
# taking care of any service aliases (do not use os.path.realpath()).
ena = set()
for el in glob.glob(os.path.join(SERVICE_DIR, name)):
if _is_svc(el):
ena.add(os.readlink(el))
log.trace('found enabled service path: %s', el)
if status == 'ENABLED':
return sorted(ena)
# path list of available services as /AVAIL_SVR_DIRS/$service
ava = set()
for d in AVAIL_SVR_DIRS:
for el in glob.glob(os.path.join(d, name)):
if _is_svc(el):
ava.add(el)
log.trace('found available service path: %s', el)
if status == 'DISABLED':
# service available but not enabled
ret = ava.difference(ena)
else:
# default: return available services
ret = ava.union(ena)
return sorted(ret) | [
"def",
"_get_svc_path",
"(",
"name",
"=",
"'*'",
",",
"status",
"=",
"None",
")",
":",
"# This is the core routine to work with services, called by many",
"# other functions of this module.",
"#",
"# The name of a service is the \"apparent\" folder's name that contains its",
"# \"run... | Return a list of paths to services with ``name`` that have the specified ``status``
name
a glob for service name. default is '*'
status
None : all services (no filter, default choice)
'DISABLED' : available service(s) that is not enabled
'ENABLED' : enabled service (whether started on boot or not) | [
"Return",
"a",
"list",
"of",
"paths",
"to",
"services",
"with",
"name",
"that",
"have",
"the",
"specified",
"status"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L325-L374 | train |
saltstack/salt | salt/modules/runit.py | _get_svc_list | def _get_svc_list(name='*', status=None):
'''
Return list of services that have the specified service ``status``
name
a glob for service name. default is '*'
status
None : all services (no filter, default choice)
'DISABLED' : available service that is not enabled
'ENABLED' : enabled service (whether started on boot or not)
'''
return sorted([os.path.basename(el) for el in _get_svc_path(name, status)]) | python | def _get_svc_list(name='*', status=None):
'''
Return list of services that have the specified service ``status``
name
a glob for service name. default is '*'
status
None : all services (no filter, default choice)
'DISABLED' : available service that is not enabled
'ENABLED' : enabled service (whether started on boot or not)
'''
return sorted([os.path.basename(el) for el in _get_svc_path(name, status)]) | [
"def",
"_get_svc_list",
"(",
"name",
"=",
"'*'",
",",
"status",
"=",
"None",
")",
":",
"return",
"sorted",
"(",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"el",
")",
"for",
"el",
"in",
"_get_svc_path",
"(",
"name",
",",
"status",
")",
"]",
")"
] | Return list of services that have the specified service ``status``
name
a glob for service name. default is '*'
status
None : all services (no filter, default choice)
'DISABLED' : available service that is not enabled
'ENABLED' : enabled service (whether started on boot or not) | [
"Return",
"list",
"of",
"services",
"that",
"have",
"the",
"specified",
"service",
"status"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L377-L389 | train |
saltstack/salt | salt/modules/runit.py | get_svc_alias | def get_svc_alias():
'''
Returns the list of service's name that are aliased and their alias path(s)
'''
ret = {}
for d in AVAIL_SVR_DIRS:
for el in glob.glob(os.path.join(d, '*')):
if not os.path.islink(el):
continue
psvc = os.readlink(el)
if not os.path.isabs(psvc):
psvc = os.path.join(d, psvc)
nsvc = os.path.basename(psvc)
if nsvc not in ret:
ret[nsvc] = []
ret[nsvc].append(el)
return ret | python | def get_svc_alias():
'''
Returns the list of service's name that are aliased and their alias path(s)
'''
ret = {}
for d in AVAIL_SVR_DIRS:
for el in glob.glob(os.path.join(d, '*')):
if not os.path.islink(el):
continue
psvc = os.readlink(el)
if not os.path.isabs(psvc):
psvc = os.path.join(d, psvc)
nsvc = os.path.basename(psvc)
if nsvc not in ret:
ret[nsvc] = []
ret[nsvc].append(el)
return ret | [
"def",
"get_svc_alias",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"d",
"in",
"AVAIL_SVR_DIRS",
":",
"for",
"el",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"'*'",
")",
")",
":",
"if",
"not",
"os",
".",
"p... | Returns the list of service's name that are aliased and their alias path(s) | [
"Returns",
"the",
"list",
"of",
"service",
"s",
"name",
"that",
"are",
"aliased",
"and",
"their",
"alias",
"path",
"(",
"s",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L392-L409 | train |
saltstack/salt | salt/modules/runit.py | show | def show(name):
'''
Show properties of one or more units/jobs or the manager
name
the service's name
CLI Example:
salt '*' service.show <service name>
'''
ret = {}
ret['enabled'] = False
ret['disabled'] = True
ret['running'] = False
ret['service_path'] = None
ret['autostart'] = False
ret['command_path'] = None
ret['available'] = available(name)
if not ret['available']:
return ret
ret['enabled'] = enabled(name)
ret['disabled'] = not ret['enabled']
ret['running'] = status(name)
ret['autostart'] = status_autostart(name)
ret['service_path'] = _get_svc_path(name)[0]
if ret['service_path']:
ret['command_path'] = os.path.join(ret['service_path'], 'run')
# XXX provide info about alias ?
return ret | python | def show(name):
'''
Show properties of one or more units/jobs or the manager
name
the service's name
CLI Example:
salt '*' service.show <service name>
'''
ret = {}
ret['enabled'] = False
ret['disabled'] = True
ret['running'] = False
ret['service_path'] = None
ret['autostart'] = False
ret['command_path'] = None
ret['available'] = available(name)
if not ret['available']:
return ret
ret['enabled'] = enabled(name)
ret['disabled'] = not ret['enabled']
ret['running'] = status(name)
ret['autostart'] = status_autostart(name)
ret['service_path'] = _get_svc_path(name)[0]
if ret['service_path']:
ret['command_path'] = os.path.join(ret['service_path'], 'run')
# XXX provide info about alias ?
return ret | [
"def",
"show",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'enabled'",
"]",
"=",
"False",
"ret",
"[",
"'disabled'",
"]",
"=",
"True",
"ret",
"[",
"'running'",
"]",
"=",
"False",
"ret",
"[",
"'service_path'",
"]",
"=",
"None",
"ret",
... | Show properties of one or more units/jobs or the manager
name
the service's name
CLI Example:
salt '*' service.show <service name> | [
"Show",
"properties",
"of",
"one",
"or",
"more",
"units",
"/",
"jobs",
"or",
"the",
"manager"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L520-L553 | train |
saltstack/salt | salt/modules/runit.py | enable | def enable(name, start=False, **kwargs):
'''
Start service ``name`` at boot.
Returns ``True`` if operation is successful
name
the service's name
start : False
If ``True``, start the service once enabled.
CLI Example:
.. code-block:: bash
salt '*' service.enable <name> [start=True]
'''
# non-existent service
if not available(name):
return False
# if service is aliased, refuse to enable it
alias = get_svc_alias()
if name in alias:
log.error('This service is aliased, enable its alias instead')
return False
# down_file: file that disables sv autostart
svc_realpath = _get_svc_path(name)[0]
down_file = os.path.join(svc_realpath, 'down')
# if service already enabled, remove down_file to
# let service starts on boot (as requested)
if enabled(name):
if os.path.exists(down_file):
try:
os.unlink(down_file)
except OSError:
log.error('Unable to remove file %s', down_file)
return False
return True
# let's enable the service
if not start:
# create a temp 'down' file BEFORE enabling service.
# will prevent sv from starting this service automatically.
log.trace('need a temporary file %s', down_file)
if not os.path.exists(down_file):
try:
salt.utils.files.fopen(down_file, "w").close() # pylint: disable=resource-leakage
except IOError:
log.error('Unable to create file %s', down_file)
return False
# enable the service
try:
os.symlink(svc_realpath, _service_path(name))
except IOError:
# (attempt to) remove temp down_file anyway
log.error('Unable to create symlink %s', down_file)
if not start:
os.unlink(down_file)
return False
# ensure sv is aware of this new service before continuing.
# if not, down_file might be removed too quickly,
# before 'sv' have time to take care about it.
# Documentation indicates that a change is handled within 5 seconds.
cmd = 'sv status {0}'.format(_service_path(name))
retcode_sv = 1
count_sv = 0
while retcode_sv != 0 and count_sv < 10:
time.sleep(0.5)
count_sv += 1
call = __salt__['cmd.run_all'](cmd)
retcode_sv = call['retcode']
# remove the temp down_file in any case.
if (not start) and os.path.exists(down_file):
try:
os.unlink(down_file)
except OSError:
log.error('Unable to remove temp file %s', down_file)
retcode_sv = 1
# if an error happened, revert our changes
if retcode_sv != 0:
os.unlink(os.path.join([_service_path(name), name]))
return False
return True | python | def enable(name, start=False, **kwargs):
'''
Start service ``name`` at boot.
Returns ``True`` if operation is successful
name
the service's name
start : False
If ``True``, start the service once enabled.
CLI Example:
.. code-block:: bash
salt '*' service.enable <name> [start=True]
'''
# non-existent service
if not available(name):
return False
# if service is aliased, refuse to enable it
alias = get_svc_alias()
if name in alias:
log.error('This service is aliased, enable its alias instead')
return False
# down_file: file that disables sv autostart
svc_realpath = _get_svc_path(name)[0]
down_file = os.path.join(svc_realpath, 'down')
# if service already enabled, remove down_file to
# let service starts on boot (as requested)
if enabled(name):
if os.path.exists(down_file):
try:
os.unlink(down_file)
except OSError:
log.error('Unable to remove file %s', down_file)
return False
return True
# let's enable the service
if not start:
# create a temp 'down' file BEFORE enabling service.
# will prevent sv from starting this service automatically.
log.trace('need a temporary file %s', down_file)
if not os.path.exists(down_file):
try:
salt.utils.files.fopen(down_file, "w").close() # pylint: disable=resource-leakage
except IOError:
log.error('Unable to create file %s', down_file)
return False
# enable the service
try:
os.symlink(svc_realpath, _service_path(name))
except IOError:
# (attempt to) remove temp down_file anyway
log.error('Unable to create symlink %s', down_file)
if not start:
os.unlink(down_file)
return False
# ensure sv is aware of this new service before continuing.
# if not, down_file might be removed too quickly,
# before 'sv' have time to take care about it.
# Documentation indicates that a change is handled within 5 seconds.
cmd = 'sv status {0}'.format(_service_path(name))
retcode_sv = 1
count_sv = 0
while retcode_sv != 0 and count_sv < 10:
time.sleep(0.5)
count_sv += 1
call = __salt__['cmd.run_all'](cmd)
retcode_sv = call['retcode']
# remove the temp down_file in any case.
if (not start) and os.path.exists(down_file):
try:
os.unlink(down_file)
except OSError:
log.error('Unable to remove temp file %s', down_file)
retcode_sv = 1
# if an error happened, revert our changes
if retcode_sv != 0:
os.unlink(os.path.join([_service_path(name), name]))
return False
return True | [
"def",
"enable",
"(",
"name",
",",
"start",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# non-existent service",
"if",
"not",
"available",
"(",
"name",
")",
":",
"return",
"False",
"# if service is aliased, refuse to enable it",
"alias",
"=",
"get_svc_alia... | Start service ``name`` at boot.
Returns ``True`` if operation is successful
name
the service's name
start : False
If ``True``, start the service once enabled.
CLI Example:
.. code-block:: bash
salt '*' service.enable <name> [start=True] | [
"Start",
"service",
"name",
"at",
"boot",
".",
"Returns",
"True",
"if",
"operation",
"is",
"successful"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L556-L648 | train |
saltstack/salt | salt/modules/runit.py | disable | def disable(name, stop=False, **kwargs):
'''
Don't start service ``name`` at boot
Returns ``True`` if operation is successful
name
the service's name
stop
if True, also stops the service
CLI Example:
.. code-block:: bash
salt '*' service.disable <name> [stop=True]
'''
# non-existent as registrered service
if not enabled(name):
return False
# down_file: file that prevent sv autostart
svc_realpath = _get_svc_path(name)[0]
down_file = os.path.join(svc_realpath, 'down')
if stop:
stop(name)
if not os.path.exists(down_file):
try:
salt.utils.files.fopen(down_file, "w").close() # pylint: disable=resource-leakage
except IOError:
log.error('Unable to create file %s', down_file)
return False
return True | python | def disable(name, stop=False, **kwargs):
'''
Don't start service ``name`` at boot
Returns ``True`` if operation is successful
name
the service's name
stop
if True, also stops the service
CLI Example:
.. code-block:: bash
salt '*' service.disable <name> [stop=True]
'''
# non-existent as registrered service
if not enabled(name):
return False
# down_file: file that prevent sv autostart
svc_realpath = _get_svc_path(name)[0]
down_file = os.path.join(svc_realpath, 'down')
if stop:
stop(name)
if not os.path.exists(down_file):
try:
salt.utils.files.fopen(down_file, "w").close() # pylint: disable=resource-leakage
except IOError:
log.error('Unable to create file %s', down_file)
return False
return True | [
"def",
"disable",
"(",
"name",
",",
"stop",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# non-existent as registrered service",
"if",
"not",
"enabled",
"(",
"name",
")",
":",
"return",
"False",
"# down_file: file that prevent sv autostart",
"svc_realpath",
"... | Don't start service ``name`` at boot
Returns ``True`` if operation is successful
name
the service's name
stop
if True, also stops the service
CLI Example:
.. code-block:: bash
salt '*' service.disable <name> [stop=True] | [
"Don",
"t",
"start",
"service",
"name",
"at",
"boot",
"Returns",
"True",
"if",
"operation",
"is",
"successful"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L651-L687 | train |
saltstack/salt | salt/modules/runit.py | remove | def remove(name):
'''
Remove the service <name> from system.
Returns ``True`` if operation is successful.
The service will be also stopped.
name
the service's name
CLI Example:
.. code-block:: bash
salt '*' service.remove <name>
'''
if not enabled(name):
return False
svc_path = _service_path(name)
if not os.path.islink(svc_path):
log.error('%s is not a symlink: not removed', svc_path)
return False
if not stop(name):
log.error('Failed to stop service %s', name)
return False
try:
os.remove(svc_path)
except IOError:
log.error('Unable to remove symlink %s', svc_path)
return False
return True | python | def remove(name):
'''
Remove the service <name> from system.
Returns ``True`` if operation is successful.
The service will be also stopped.
name
the service's name
CLI Example:
.. code-block:: bash
salt '*' service.remove <name>
'''
if not enabled(name):
return False
svc_path = _service_path(name)
if not os.path.islink(svc_path):
log.error('%s is not a symlink: not removed', svc_path)
return False
if not stop(name):
log.error('Failed to stop service %s', name)
return False
try:
os.remove(svc_path)
except IOError:
log.error('Unable to remove symlink %s', svc_path)
return False
return True | [
"def",
"remove",
"(",
"name",
")",
":",
"if",
"not",
"enabled",
"(",
"name",
")",
":",
"return",
"False",
"svc_path",
"=",
"_service_path",
"(",
"name",
")",
"if",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"svc_path",
")",
":",
"log",
".",
"err... | Remove the service <name> from system.
Returns ``True`` if operation is successful.
The service will be also stopped.
name
the service's name
CLI Example:
.. code-block:: bash
salt '*' service.remove <name> | [
"Remove",
"the",
"service",
"<name",
">",
"from",
"system",
".",
"Returns",
"True",
"if",
"operation",
"is",
"successful",
".",
"The",
"service",
"will",
"be",
"also",
"stopped",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L690-L722 | train |
saltstack/salt | salt/pillar/s3.py | ext_pillar | def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
bucket,
key=None,
keyid=None,
verify_ssl=True,
location=None,
multiple_env=False,
environment='base',
prefix='',
service_url=None,
kms_keyid=None,
s3_cache_expire=30, # cache for 30 seconds
s3_sync_on_update=True, # sync cache on update rather than jit
path_style=False,
https_enable=True):
'''
Execute a command and read the output as YAML
'''
s3_creds = S3Credentials(key, keyid, bucket, service_url, verify_ssl,
kms_keyid, location, path_style, https_enable)
# normpath is needed to remove appended '/' if root is empty string.
pillar_dir = os.path.normpath(os.path.join(_get_cache_dir(), environment,
bucket))
if prefix:
pillar_dir = os.path.normpath(os.path.join(pillar_dir, prefix))
if __opts__['pillar_roots'].get(environment, []) == [pillar_dir]:
return {}
metadata = _init(s3_creds, bucket, multiple_env, environment, prefix, s3_cache_expire)
if s3_sync_on_update:
# sync the buckets to the local cache
log.info('Syncing local pillar cache from S3...')
for saltenv, env_meta in six.iteritems(metadata):
for bucket, files in six.iteritems(_find_files(env_meta)):
for file_path in files:
cached_file_path = _get_cached_file_name(bucket, saltenv,
file_path)
log.info('%s - %s : %s', bucket, saltenv, file_path)
# load the file from S3 if not in the cache or too old
_get_file_from_s3(s3_creds, metadata, saltenv, bucket,
file_path, cached_file_path)
log.info('Sync local pillar cache from S3 completed.')
opts = deepcopy(__opts__)
opts['pillar_roots'][environment] = [os.path.join(pillar_dir, environment)] if multiple_env else [pillar_dir]
# Avoid recursively re-adding this same pillar
opts['ext_pillar'] = [x for x in opts['ext_pillar'] if 's3' not in x]
pil = Pillar(opts, __grains__, minion_id, environment)
compiled_pillar = pil.compile_pillar(ext=False)
return compiled_pillar | python | def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
bucket,
key=None,
keyid=None,
verify_ssl=True,
location=None,
multiple_env=False,
environment='base',
prefix='',
service_url=None,
kms_keyid=None,
s3_cache_expire=30, # cache for 30 seconds
s3_sync_on_update=True, # sync cache on update rather than jit
path_style=False,
https_enable=True):
'''
Execute a command and read the output as YAML
'''
s3_creds = S3Credentials(key, keyid, bucket, service_url, verify_ssl,
kms_keyid, location, path_style, https_enable)
# normpath is needed to remove appended '/' if root is empty string.
pillar_dir = os.path.normpath(os.path.join(_get_cache_dir(), environment,
bucket))
if prefix:
pillar_dir = os.path.normpath(os.path.join(pillar_dir, prefix))
if __opts__['pillar_roots'].get(environment, []) == [pillar_dir]:
return {}
metadata = _init(s3_creds, bucket, multiple_env, environment, prefix, s3_cache_expire)
if s3_sync_on_update:
# sync the buckets to the local cache
log.info('Syncing local pillar cache from S3...')
for saltenv, env_meta in six.iteritems(metadata):
for bucket, files in six.iteritems(_find_files(env_meta)):
for file_path in files:
cached_file_path = _get_cached_file_name(bucket, saltenv,
file_path)
log.info('%s - %s : %s', bucket, saltenv, file_path)
# load the file from S3 if not in the cache or too old
_get_file_from_s3(s3_creds, metadata, saltenv, bucket,
file_path, cached_file_path)
log.info('Sync local pillar cache from S3 completed.')
opts = deepcopy(__opts__)
opts['pillar_roots'][environment] = [os.path.join(pillar_dir, environment)] if multiple_env else [pillar_dir]
# Avoid recursively re-adding this same pillar
opts['ext_pillar'] = [x for x in opts['ext_pillar'] if 's3' not in x]
pil = Pillar(opts, __grains__, minion_id, environment)
compiled_pillar = pil.compile_pillar(ext=False)
return compiled_pillar | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"# pylint: disable=W0613",
"bucket",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"verify_ssl",
"=",
"True",
",",
"location",
"=",
"None",
",",
"multiple_env",
"=",
"False",
",",
"envir... | Execute a command and read the output as YAML | [
"Execute",
"a",
"command",
"and",
"read",
"the",
"output",
"as",
"YAML"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L129-L189 | train |
saltstack/salt | salt/pillar/s3.py | _init | def _init(creds, bucket, multiple_env, environment, prefix, s3_cache_expire):
'''
Connect to S3 and download the metadata for each file in all buckets
specified and cache the data to disk.
'''
cache_file = _get_buckets_cache_filename(bucket, prefix)
exp = time.time() - s3_cache_expire
# check if cache_file exists and its mtime
if os.path.isfile(cache_file):
cache_file_mtime = os.path.getmtime(cache_file)
else:
# file does not exists then set mtime to 0 (aka epoch)
cache_file_mtime = 0
expired = (cache_file_mtime <= exp)
log.debug(
'S3 bucket cache file %s is %sexpired, mtime_diff=%ss, expiration=%ss',
cache_file,
'' if expired else 'not ',
cache_file_mtime - exp,
s3_cache_expire
)
if expired:
pillars = _refresh_buckets_cache_file(creds, cache_file, multiple_env,
environment, prefix)
else:
pillars = _read_buckets_cache_file(cache_file)
log.debug('S3 bucket retrieved pillars %s', pillars)
return pillars | python | def _init(creds, bucket, multiple_env, environment, prefix, s3_cache_expire):
'''
Connect to S3 and download the metadata for each file in all buckets
specified and cache the data to disk.
'''
cache_file = _get_buckets_cache_filename(bucket, prefix)
exp = time.time() - s3_cache_expire
# check if cache_file exists and its mtime
if os.path.isfile(cache_file):
cache_file_mtime = os.path.getmtime(cache_file)
else:
# file does not exists then set mtime to 0 (aka epoch)
cache_file_mtime = 0
expired = (cache_file_mtime <= exp)
log.debug(
'S3 bucket cache file %s is %sexpired, mtime_diff=%ss, expiration=%ss',
cache_file,
'' if expired else 'not ',
cache_file_mtime - exp,
s3_cache_expire
)
if expired:
pillars = _refresh_buckets_cache_file(creds, cache_file, multiple_env,
environment, prefix)
else:
pillars = _read_buckets_cache_file(cache_file)
log.debug('S3 bucket retrieved pillars %s', pillars)
return pillars | [
"def",
"_init",
"(",
"creds",
",",
"bucket",
",",
"multiple_env",
",",
"environment",
",",
"prefix",
",",
"s3_cache_expire",
")",
":",
"cache_file",
"=",
"_get_buckets_cache_filename",
"(",
"bucket",
",",
"prefix",
")",
"exp",
"=",
"time",
".",
"time",
"(",
... | Connect to S3 and download the metadata for each file in all buckets
specified and cache the data to disk. | [
"Connect",
"to",
"S3",
"and",
"download",
"the",
"metadata",
"for",
"each",
"file",
"in",
"all",
"buckets",
"specified",
"and",
"cache",
"the",
"data",
"to",
"disk",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L192-L225 | train |
saltstack/salt | salt/pillar/s3.py | _get_cache_dir | def _get_cache_dir():
'''
Get pillar cache directory. Initialize it if it does not exist.
'''
cache_dir = os.path.join(__opts__['cachedir'], 'pillar_s3fs')
if not os.path.isdir(cache_dir):
log.debug('Initializing S3 Pillar Cache')
os.makedirs(cache_dir)
return cache_dir | python | def _get_cache_dir():
'''
Get pillar cache directory. Initialize it if it does not exist.
'''
cache_dir = os.path.join(__opts__['cachedir'], 'pillar_s3fs')
if not os.path.isdir(cache_dir):
log.debug('Initializing S3 Pillar Cache')
os.makedirs(cache_dir)
return cache_dir | [
"def",
"_get_cache_dir",
"(",
")",
":",
"cache_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'pillar_s3fs'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"cache_dir",
")",
":",
"log",
".",
"debug... | Get pillar cache directory. Initialize it if it does not exist. | [
"Get",
"pillar",
"cache",
"directory",
".",
"Initialize",
"it",
"if",
"it",
"does",
"not",
"exist",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L228-L239 | train |
saltstack/salt | salt/pillar/s3.py | _get_buckets_cache_filename | def _get_buckets_cache_filename(bucket, prefix):
'''
Return the filename of the cache for bucket contents.
Create the path if it does not exist.
'''
cache_dir = _get_cache_dir()
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
return os.path.join(cache_dir, '{0}-{1}-files.cache'.format(bucket, prefix)) | python | def _get_buckets_cache_filename(bucket, prefix):
'''
Return the filename of the cache for bucket contents.
Create the path if it does not exist.
'''
cache_dir = _get_cache_dir()
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
return os.path.join(cache_dir, '{0}-{1}-files.cache'.format(bucket, prefix)) | [
"def",
"_get_buckets_cache_filename",
"(",
"bucket",
",",
"prefix",
")",
":",
"cache_dir",
"=",
"_get_cache_dir",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cache_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"cache_dir",
")",
"return",
... | Return the filename of the cache for bucket contents.
Create the path if it does not exist. | [
"Return",
"the",
"filename",
"of",
"the",
"cache",
"for",
"bucket",
"contents",
".",
"Create",
"the",
"path",
"if",
"it",
"does",
"not",
"exist",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L256-L266 | train |
saltstack/salt | salt/pillar/s3.py | _refresh_buckets_cache_file | def _refresh_buckets_cache_file(creds, cache_file, multiple_env, environment, prefix):
'''
Retrieve the content of all buckets and cache the metadata to the buckets
cache file
'''
# helper s3 query function
def __get_s3_meta():
return __utils__['s3.query'](
key=creds.key,
keyid=creds.keyid,
kms_keyid=creds.kms_keyid,
bucket=creds.bucket,
service_url=creds.service_url,
verify_ssl=creds.verify_ssl,
location=creds.location,
return_bin=False,
params={'prefix': prefix},
path_style=creds.path_style,
https_enable=creds.https_enable)
# grab only the files/dirs in the bucket
def __get_pillar_files_from_s3_meta(s3_meta):
return [k for k in s3_meta if 'Key' in k]
# pull out the environment dirs (e.g. the root dirs)
def __get_pillar_environments(files):
environments = [(os.path.dirname(k['Key']).split('/', 1))[0] for k in files]
return set(environments)
log.debug('Refreshing S3 buckets pillar cache file')
metadata = {}
bucket = creds.bucket
if not multiple_env:
# Single environment per bucket
log.debug('Single environment per bucket mode')
bucket_files = {}
s3_meta = __get_s3_meta()
# s3 query returned something
if s3_meta:
bucket_files[bucket] = __get_pillar_files_from_s3_meta(s3_meta)
metadata[environment] = bucket_files
else:
# Multiple environments per buckets
log.debug('Multiple environment per bucket mode')
s3_meta = __get_s3_meta()
# s3 query returned data
if s3_meta:
files = __get_pillar_files_from_s3_meta(s3_meta)
environments = __get_pillar_environments(files)
# pull out the files for the environment
for saltenv in environments:
# grab only files/dirs that match this saltenv.
env_files = [k for k in files if k['Key'].startswith(saltenv)]
if saltenv not in metadata:
metadata[saltenv] = {}
if bucket not in metadata[saltenv]:
metadata[saltenv][bucket] = []
metadata[saltenv][bucket] += env_files
# write the metadata to disk
if os.path.isfile(cache_file):
os.remove(cache_file)
log.debug('Writing S3 buckets pillar cache file')
with salt.utils.files.fopen(cache_file, 'w') as fp_:
pickle.dump(metadata, fp_)
return metadata | python | def _refresh_buckets_cache_file(creds, cache_file, multiple_env, environment, prefix):
'''
Retrieve the content of all buckets and cache the metadata to the buckets
cache file
'''
# helper s3 query function
def __get_s3_meta():
return __utils__['s3.query'](
key=creds.key,
keyid=creds.keyid,
kms_keyid=creds.kms_keyid,
bucket=creds.bucket,
service_url=creds.service_url,
verify_ssl=creds.verify_ssl,
location=creds.location,
return_bin=False,
params={'prefix': prefix},
path_style=creds.path_style,
https_enable=creds.https_enable)
# grab only the files/dirs in the bucket
def __get_pillar_files_from_s3_meta(s3_meta):
return [k for k in s3_meta if 'Key' in k]
# pull out the environment dirs (e.g. the root dirs)
def __get_pillar_environments(files):
environments = [(os.path.dirname(k['Key']).split('/', 1))[0] for k in files]
return set(environments)
log.debug('Refreshing S3 buckets pillar cache file')
metadata = {}
bucket = creds.bucket
if not multiple_env:
# Single environment per bucket
log.debug('Single environment per bucket mode')
bucket_files = {}
s3_meta = __get_s3_meta()
# s3 query returned something
if s3_meta:
bucket_files[bucket] = __get_pillar_files_from_s3_meta(s3_meta)
metadata[environment] = bucket_files
else:
# Multiple environments per buckets
log.debug('Multiple environment per bucket mode')
s3_meta = __get_s3_meta()
# s3 query returned data
if s3_meta:
files = __get_pillar_files_from_s3_meta(s3_meta)
environments = __get_pillar_environments(files)
# pull out the files for the environment
for saltenv in environments:
# grab only files/dirs that match this saltenv.
env_files = [k for k in files if k['Key'].startswith(saltenv)]
if saltenv not in metadata:
metadata[saltenv] = {}
if bucket not in metadata[saltenv]:
metadata[saltenv][bucket] = []
metadata[saltenv][bucket] += env_files
# write the metadata to disk
if os.path.isfile(cache_file):
os.remove(cache_file)
log.debug('Writing S3 buckets pillar cache file')
with salt.utils.files.fopen(cache_file, 'w') as fp_:
pickle.dump(metadata, fp_)
return metadata | [
"def",
"_refresh_buckets_cache_file",
"(",
"creds",
",",
"cache_file",
",",
"multiple_env",
",",
"environment",
",",
"prefix",
")",
":",
"# helper s3 query function",
"def",
"__get_s3_meta",
"(",
")",
":",
"return",
"__utils__",
"[",
"'s3.query'",
"]",
"(",
"key",... | Retrieve the content of all buckets and cache the metadata to the buckets
cache file | [
"Retrieve",
"the",
"content",
"of",
"all",
"buckets",
"and",
"cache",
"the",
"metadata",
"to",
"the",
"buckets",
"cache",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L269-L349 | train |
saltstack/salt | salt/pillar/s3.py | _read_buckets_cache_file | def _read_buckets_cache_file(cache_file):
'''
Return the contents of the buckets cache file
'''
log.debug('Reading buckets cache file')
with salt.utils.files.fopen(cache_file, 'rb') as fp_:
data = pickle.load(fp_)
return data | python | def _read_buckets_cache_file(cache_file):
'''
Return the contents of the buckets cache file
'''
log.debug('Reading buckets cache file')
with salt.utils.files.fopen(cache_file, 'rb') as fp_:
data = pickle.load(fp_)
return data | [
"def",
"_read_buckets_cache_file",
"(",
"cache_file",
")",
":",
"log",
".",
"debug",
"(",
"'Reading buckets cache file'",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"cache_file",
",",
"'rb'",
")",
"as",
"fp_",
":",
"data",
"=",
"pi... | Return the contents of the buckets cache file | [
"Return",
"the",
"contents",
"of",
"the",
"buckets",
"cache",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L352-L362 | train |
saltstack/salt | salt/pillar/s3.py | _find_files | def _find_files(metadata):
'''
Looks for all the files in the S3 bucket cache metadata
'''
ret = {}
for bucket, data in six.iteritems(metadata):
if bucket not in ret:
ret[bucket] = []
# grab the paths from the metadata
filePaths = [k['Key'] for k in data]
# filter out the dirs
ret[bucket] += [k for k in filePaths if not k.endswith('/')]
return ret | python | def _find_files(metadata):
'''
Looks for all the files in the S3 bucket cache metadata
'''
ret = {}
for bucket, data in six.iteritems(metadata):
if bucket not in ret:
ret[bucket] = []
# grab the paths from the metadata
filePaths = [k['Key'] for k in data]
# filter out the dirs
ret[bucket] += [k for k in filePaths if not k.endswith('/')]
return ret | [
"def",
"_find_files",
"(",
"metadata",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"bucket",
",",
"data",
"in",
"six",
".",
"iteritems",
"(",
"metadata",
")",
":",
"if",
"bucket",
"not",
"in",
"ret",
":",
"ret",
"[",
"bucket",
"]",
"=",
"[",
"]",
"# g... | Looks for all the files in the S3 bucket cache metadata | [
"Looks",
"for",
"all",
"the",
"files",
"in",
"the",
"S3",
"bucket",
"cache",
"metadata"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L365-L381 | train |
saltstack/salt | salt/pillar/s3.py | _get_file_from_s3 | def _get_file_from_s3(creds, metadata, saltenv, bucket, path,
cached_file_path):
'''
Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache
'''
# check the local cache...
if os.path.isfile(cached_file_path):
file_meta = _find_file_meta(metadata, bucket, saltenv, path)
file_md5 = "".join(list(filter(str.isalnum, file_meta['ETag']))) \
if file_meta else None
cached_md5 = salt.utils.hashutils.get_hash(cached_file_path, 'md5')
# hashes match we have a cache hit
log.debug('Cached file: path=%s, md5=%s, etag=%s',
cached_file_path, cached_md5, file_md5)
if cached_md5 == file_md5:
return
# ... or get the file from S3
__utils__['s3.query'](
key=creds.key,
keyid=creds.keyid,
kms_keyid=creds.kms_keyid,
bucket=bucket,
service_url=creds.service_url,
path=_quote(path),
local_file=cached_file_path,
verify_ssl=creds.verify_ssl,
location=creds.location,
path_style=creds.path_style,
https_enable=creds.https_enable
) | python | def _get_file_from_s3(creds, metadata, saltenv, bucket, path,
cached_file_path):
'''
Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache
'''
# check the local cache...
if os.path.isfile(cached_file_path):
file_meta = _find_file_meta(metadata, bucket, saltenv, path)
file_md5 = "".join(list(filter(str.isalnum, file_meta['ETag']))) \
if file_meta else None
cached_md5 = salt.utils.hashutils.get_hash(cached_file_path, 'md5')
# hashes match we have a cache hit
log.debug('Cached file: path=%s, md5=%s, etag=%s',
cached_file_path, cached_md5, file_md5)
if cached_md5 == file_md5:
return
# ... or get the file from S3
__utils__['s3.query'](
key=creds.key,
keyid=creds.keyid,
kms_keyid=creds.kms_keyid,
bucket=bucket,
service_url=creds.service_url,
path=_quote(path),
local_file=cached_file_path,
verify_ssl=creds.verify_ssl,
location=creds.location,
path_style=creds.path_style,
https_enable=creds.https_enable
) | [
"def",
"_get_file_from_s3",
"(",
"creds",
",",
"metadata",
",",
"saltenv",
",",
"bucket",
",",
"path",
",",
"cached_file_path",
")",
":",
"# check the local cache...",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"cached_file_path",
")",
":",
"file_meta",
"=",... | Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache | [
"Checks",
"the",
"local",
"cache",
"for",
"the",
"file",
"if",
"it",
"s",
"old",
"or",
"missing",
"go",
"grab",
"the",
"file",
"from",
"S3",
"and",
"update",
"the",
"cache"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L398-L432 | train |
saltstack/salt | salt/modules/logadm.py | _arg2opt | def _arg2opt(arg):
'''
Turn a pass argument into the correct option
'''
res = [o for o, a in option_toggles.items() if a == arg]
res += [o for o, a in option_flags.items() if a == arg]
return res[0] if res else None | python | def _arg2opt(arg):
'''
Turn a pass argument into the correct option
'''
res = [o for o, a in option_toggles.items() if a == arg]
res += [o for o, a in option_flags.items() if a == arg]
return res[0] if res else None | [
"def",
"_arg2opt",
"(",
"arg",
")",
":",
"res",
"=",
"[",
"o",
"for",
"o",
",",
"a",
"in",
"option_toggles",
".",
"items",
"(",
")",
"if",
"a",
"==",
"arg",
"]",
"res",
"+=",
"[",
"o",
"for",
"o",
",",
"a",
"in",
"option_flags",
".",
"items",
... | Turn a pass argument into the correct option | [
"Turn",
"a",
"pass",
"argument",
"into",
"the",
"correct",
"option"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L61-L67 | train |
saltstack/salt | salt/modules/logadm.py | _parse_conf | def _parse_conf(conf_file=default_conf):
'''
Parse a logadm configuration file.
'''
ret = {}
with salt.utils.files.fopen(conf_file, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line).strip()
if not line:
continue
if line.startswith('#'):
continue
splitline = line.split(' ', 1)
ret[splitline[0]] = splitline[1]
return ret | python | def _parse_conf(conf_file=default_conf):
'''
Parse a logadm configuration file.
'''
ret = {}
with salt.utils.files.fopen(conf_file, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line).strip()
if not line:
continue
if line.startswith('#'):
continue
splitline = line.split(' ', 1)
ret[splitline[0]] = splitline[1]
return ret | [
"def",
"_parse_conf",
"(",
"conf_file",
"=",
"default_conf",
")",
":",
"ret",
"=",
"{",
"}",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"conf_file",
",",
"'r'",
")",
"as",
"ifile",
":",
"for",
"line",
"in",
"ifile",
":",
"line",
... | Parse a logadm configuration file. | [
"Parse",
"a",
"logadm",
"configuration",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L70-L84 | train |
saltstack/salt | salt/modules/logadm.py | _parse_options | def _parse_options(entry, options, include_unset=True):
'''
Parse a logadm options string
'''
log_cfg = {}
options = shlex.split(options)
if not options:
return None
## identifier is entry or log?
if entry.startswith('/'):
log_cfg['log_file'] = entry
else:
log_cfg['entryname'] = entry
## parse options
# NOTE: we loop over the options because values may exist multiple times
index = 0
while index < len(options):
# log file
if index in [0, (len(options)-1)] and options[index].startswith('/'):
log_cfg['log_file'] = options[index]
# check if toggle option
elif options[index] in option_toggles:
log_cfg[option_toggles[options[index]]] = True
# check if flag option
elif options[index] in option_flags and (index+1) <= len(options):
log_cfg[option_flags[options[index]]] = int(options[index+1]) if options[index+1].isdigit() else options[index+1]
index += 1
# unknown options
else:
if 'additional_options' not in log_cfg:
log_cfg['additional_options'] = []
if ' ' in options[index]:
log_cfg['dditional_options'] = "'{}'".format(options[index])
else:
log_cfg['additional_options'].append(options[index])
index += 1
## turn additional_options into string
if 'additional_options' in log_cfg:
log_cfg['additional_options'] = " ".join(log_cfg['additional_options'])
## ensure we have a log_file
# NOTE: logadm assumes logname is a file if no log_file is given
if 'log_file' not in log_cfg and 'entryname' in log_cfg:
log_cfg['log_file'] = log_cfg['entryname']
del log_cfg['entryname']
## include unset
if include_unset:
# toggle optioons
for name in option_toggles.values():
if name not in log_cfg:
log_cfg[name] = False
# flag options
for name in option_flags.values():
if name not in log_cfg:
log_cfg[name] = None
return log_cfg | python | def _parse_options(entry, options, include_unset=True):
'''
Parse a logadm options string
'''
log_cfg = {}
options = shlex.split(options)
if not options:
return None
## identifier is entry or log?
if entry.startswith('/'):
log_cfg['log_file'] = entry
else:
log_cfg['entryname'] = entry
## parse options
# NOTE: we loop over the options because values may exist multiple times
index = 0
while index < len(options):
# log file
if index in [0, (len(options)-1)] and options[index].startswith('/'):
log_cfg['log_file'] = options[index]
# check if toggle option
elif options[index] in option_toggles:
log_cfg[option_toggles[options[index]]] = True
# check if flag option
elif options[index] in option_flags and (index+1) <= len(options):
log_cfg[option_flags[options[index]]] = int(options[index+1]) if options[index+1].isdigit() else options[index+1]
index += 1
# unknown options
else:
if 'additional_options' not in log_cfg:
log_cfg['additional_options'] = []
if ' ' in options[index]:
log_cfg['dditional_options'] = "'{}'".format(options[index])
else:
log_cfg['additional_options'].append(options[index])
index += 1
## turn additional_options into string
if 'additional_options' in log_cfg:
log_cfg['additional_options'] = " ".join(log_cfg['additional_options'])
## ensure we have a log_file
# NOTE: logadm assumes logname is a file if no log_file is given
if 'log_file' not in log_cfg and 'entryname' in log_cfg:
log_cfg['log_file'] = log_cfg['entryname']
del log_cfg['entryname']
## include unset
if include_unset:
# toggle optioons
for name in option_toggles.values():
if name not in log_cfg:
log_cfg[name] = False
# flag options
for name in option_flags.values():
if name not in log_cfg:
log_cfg[name] = None
return log_cfg | [
"def",
"_parse_options",
"(",
"entry",
",",
"options",
",",
"include_unset",
"=",
"True",
")",
":",
"log_cfg",
"=",
"{",
"}",
"options",
"=",
"shlex",
".",
"split",
"(",
"options",
")",
"if",
"not",
"options",
":",
"return",
"None",
"## identifier is entry... | Parse a logadm options string | [
"Parse",
"a",
"logadm",
"options",
"string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L87-L152 | train |
saltstack/salt | salt/modules/logadm.py | show_conf | def show_conf(conf_file=default_conf, name=None):
'''
Show configuration
conf_file : string
path to logadm.conf, defaults to /etc/logadm.conf
name : string
optional show only a single entry
CLI Example:
.. code-block:: bash
salt '*' logadm.show_conf
salt '*' logadm.show_conf name=/var/log/syslog
'''
cfg = _parse_conf(conf_file)
# filter
if name and name in cfg:
return {name: cfg[name]}
elif name:
return {name: 'not found in {}'.format(conf_file)}
else:
return cfg | python | def show_conf(conf_file=default_conf, name=None):
'''
Show configuration
conf_file : string
path to logadm.conf, defaults to /etc/logadm.conf
name : string
optional show only a single entry
CLI Example:
.. code-block:: bash
salt '*' logadm.show_conf
salt '*' logadm.show_conf name=/var/log/syslog
'''
cfg = _parse_conf(conf_file)
# filter
if name and name in cfg:
return {name: cfg[name]}
elif name:
return {name: 'not found in {}'.format(conf_file)}
else:
return cfg | [
"def",
"show_conf",
"(",
"conf_file",
"=",
"default_conf",
",",
"name",
"=",
"None",
")",
":",
"cfg",
"=",
"_parse_conf",
"(",
"conf_file",
")",
"# filter",
"if",
"name",
"and",
"name",
"in",
"cfg",
":",
"return",
"{",
"name",
":",
"cfg",
"[",
"name",
... | Show configuration
conf_file : string
path to logadm.conf, defaults to /etc/logadm.conf
name : string
optional show only a single entry
CLI Example:
.. code-block:: bash
salt '*' logadm.show_conf
salt '*' logadm.show_conf name=/var/log/syslog | [
"Show",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L155-L179 | train |
saltstack/salt | salt/modules/logadm.py | list_conf | def list_conf(conf_file=default_conf, log_file=None, include_unset=False):
'''
Show parsed configuration
.. versionadded:: 2018.3.0
conf_file : string
path to logadm.conf, defaults to /etc/logadm.conf
log_file : string
optional show only one log file
include_unset : boolean
include unset flags in output
CLI Example:
.. code-block:: bash
salt '*' logadm.list_conf
salt '*' logadm.list_conf log=/var/log/syslog
salt '*' logadm.list_conf include_unset=False
'''
cfg = _parse_conf(conf_file)
cfg_parsed = {}
## parse all options
for entry in cfg:
log_cfg = _parse_options(entry, cfg[entry], include_unset)
cfg_parsed[log_cfg['log_file'] if 'log_file' in log_cfg else log_cfg['entryname']] = log_cfg
## filter
if log_file and log_file in cfg_parsed:
return {log_file: cfg_parsed[log_file]}
elif log_file:
return {log_file: 'not found in {}'.format(conf_file)}
else:
return cfg_parsed | python | def list_conf(conf_file=default_conf, log_file=None, include_unset=False):
'''
Show parsed configuration
.. versionadded:: 2018.3.0
conf_file : string
path to logadm.conf, defaults to /etc/logadm.conf
log_file : string
optional show only one log file
include_unset : boolean
include unset flags in output
CLI Example:
.. code-block:: bash
salt '*' logadm.list_conf
salt '*' logadm.list_conf log=/var/log/syslog
salt '*' logadm.list_conf include_unset=False
'''
cfg = _parse_conf(conf_file)
cfg_parsed = {}
## parse all options
for entry in cfg:
log_cfg = _parse_options(entry, cfg[entry], include_unset)
cfg_parsed[log_cfg['log_file'] if 'log_file' in log_cfg else log_cfg['entryname']] = log_cfg
## filter
if log_file and log_file in cfg_parsed:
return {log_file: cfg_parsed[log_file]}
elif log_file:
return {log_file: 'not found in {}'.format(conf_file)}
else:
return cfg_parsed | [
"def",
"list_conf",
"(",
"conf_file",
"=",
"default_conf",
",",
"log_file",
"=",
"None",
",",
"include_unset",
"=",
"False",
")",
":",
"cfg",
"=",
"_parse_conf",
"(",
"conf_file",
")",
"cfg_parsed",
"=",
"{",
"}",
"## parse all options",
"for",
"entry",
"in"... | Show parsed configuration
.. versionadded:: 2018.3.0
conf_file : string
path to logadm.conf, defaults to /etc/logadm.conf
log_file : string
optional show only one log file
include_unset : boolean
include unset flags in output
CLI Example:
.. code-block:: bash
salt '*' logadm.list_conf
salt '*' logadm.list_conf log=/var/log/syslog
salt '*' logadm.list_conf include_unset=False | [
"Show",
"parsed",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L182-L217 | train |
saltstack/salt | salt/modules/logadm.py | show_args | def show_args():
'''
Show which arguments map to which flags and options.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' logadm.show_args
'''
mapping = {'flags': {}, 'options': {}}
for flag, arg in option_toggles.items():
mapping['flags'][flag] = arg
for option, arg in option_flags.items():
mapping['options'][option] = arg
return mapping | python | def show_args():
'''
Show which arguments map to which flags and options.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' logadm.show_args
'''
mapping = {'flags': {}, 'options': {}}
for flag, arg in option_toggles.items():
mapping['flags'][flag] = arg
for option, arg in option_flags.items():
mapping['options'][option] = arg
return mapping | [
"def",
"show_args",
"(",
")",
":",
"mapping",
"=",
"{",
"'flags'",
":",
"{",
"}",
",",
"'options'",
":",
"{",
"}",
"}",
"for",
"flag",
",",
"arg",
"in",
"option_toggles",
".",
"items",
"(",
")",
":",
"mapping",
"[",
"'flags'",
"]",
"[",
"flag",
"... | Show which arguments map to which flags and options.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' logadm.show_args | [
"Show",
"which",
"arguments",
"map",
"to",
"which",
"flags",
"and",
"options",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L221-L239 | train |
saltstack/salt | salt/modules/logadm.py | rotate | def rotate(name, pattern=None, conf_file=default_conf, **kwargs):
'''
Set up pattern for logging.
name : string
alias for entryname
pattern : string
alias for log_file
conf_file : string
optional path to alternative configuration file
kwargs : boolean|string|int
optional additional flags and parameters
.. note::
``name`` and ``pattern`` were kept for backwards compatibility reasons.
``name`` is an alias for the ``entryname`` argument, ``pattern`` is an alias
for ``log_file``. These aliases will only be used if the ``entryname`` and
``log_file`` arguments are not passed.
For a full list of arguments see ```logadm.show_args```.
CLI Example:
.. code-block:: bash
salt '*' logadm.rotate myapplog pattern='/var/log/myapp/*.log' count=7
salt '*' logadm.rotate myapplog log_file='/var/log/myapp/*.log' count=4 owner=myappd mode='0700'
'''
## cleanup kwargs
kwargs = salt.utils.args.clean_kwargs(**kwargs)
## inject name into kwargs
if 'entryname' not in kwargs and name and not name.startswith('/'):
kwargs['entryname'] = name
## inject pattern into kwargs
if 'log_file' not in kwargs:
if pattern and pattern.startswith('/'):
kwargs['log_file'] = pattern
# NOTE: for backwards compatibility check if name is a path
elif name and name.startswith('/'):
kwargs['log_file'] = name
## build command
log.debug("logadm.rotate - kwargs: %s", kwargs)
command = "logadm -f {}".format(conf_file)
for arg, val in kwargs.items():
if arg in option_toggles.values() and val:
command = "{} {}".format(
command,
_arg2opt(arg),
)
elif arg in option_flags.values():
command = "{} {} {}".format(
command,
_arg2opt(arg),
_quote_args(six.text_type(val))
)
elif arg != 'log_file':
log.warning("Unknown argument %s, don't know how to map this!", arg)
if 'log_file' in kwargs:
# NOTE: except from ```man logadm```
# If no log file name is provided on a logadm command line, the entry
# name is assumed to be the same as the log file name. For example,
# the following two lines achieve the same thing, keeping two copies
# of rotated log files:
#
# % logadm -C2 -w mylog /my/really/long/log/file/name
# % logadm -C2 -w /my/really/long/log/file/name
if 'entryname' not in kwargs:
command = "{} -w {}".format(command, _quote_args(kwargs['log_file']))
else:
command = "{} {}".format(command, _quote_args(kwargs['log_file']))
log.debug("logadm.rotate - command: %s", command)
result = __salt__['cmd.run_all'](command, python_shell=False)
if result['retcode'] != 0:
return dict(Error='Failed in adding log', Output=result['stderr'])
return dict(Result='Success') | python | def rotate(name, pattern=None, conf_file=default_conf, **kwargs):
'''
Set up pattern for logging.
name : string
alias for entryname
pattern : string
alias for log_file
conf_file : string
optional path to alternative configuration file
kwargs : boolean|string|int
optional additional flags and parameters
.. note::
``name`` and ``pattern`` were kept for backwards compatibility reasons.
``name`` is an alias for the ``entryname`` argument, ``pattern`` is an alias
for ``log_file``. These aliases will only be used if the ``entryname`` and
``log_file`` arguments are not passed.
For a full list of arguments see ```logadm.show_args```.
CLI Example:
.. code-block:: bash
salt '*' logadm.rotate myapplog pattern='/var/log/myapp/*.log' count=7
salt '*' logadm.rotate myapplog log_file='/var/log/myapp/*.log' count=4 owner=myappd mode='0700'
'''
## cleanup kwargs
kwargs = salt.utils.args.clean_kwargs(**kwargs)
## inject name into kwargs
if 'entryname' not in kwargs and name and not name.startswith('/'):
kwargs['entryname'] = name
## inject pattern into kwargs
if 'log_file' not in kwargs:
if pattern and pattern.startswith('/'):
kwargs['log_file'] = pattern
# NOTE: for backwards compatibility check if name is a path
elif name and name.startswith('/'):
kwargs['log_file'] = name
## build command
log.debug("logadm.rotate - kwargs: %s", kwargs)
command = "logadm -f {}".format(conf_file)
for arg, val in kwargs.items():
if arg in option_toggles.values() and val:
command = "{} {}".format(
command,
_arg2opt(arg),
)
elif arg in option_flags.values():
command = "{} {} {}".format(
command,
_arg2opt(arg),
_quote_args(six.text_type(val))
)
elif arg != 'log_file':
log.warning("Unknown argument %s, don't know how to map this!", arg)
if 'log_file' in kwargs:
# NOTE: except from ```man logadm```
# If no log file name is provided on a logadm command line, the entry
# name is assumed to be the same as the log file name. For example,
# the following two lines achieve the same thing, keeping two copies
# of rotated log files:
#
# % logadm -C2 -w mylog /my/really/long/log/file/name
# % logadm -C2 -w /my/really/long/log/file/name
if 'entryname' not in kwargs:
command = "{} -w {}".format(command, _quote_args(kwargs['log_file']))
else:
command = "{} {}".format(command, _quote_args(kwargs['log_file']))
log.debug("logadm.rotate - command: %s", command)
result = __salt__['cmd.run_all'](command, python_shell=False)
if result['retcode'] != 0:
return dict(Error='Failed in adding log', Output=result['stderr'])
return dict(Result='Success') | [
"def",
"rotate",
"(",
"name",
",",
"pattern",
"=",
"None",
",",
"conf_file",
"=",
"default_conf",
",",
"*",
"*",
"kwargs",
")",
":",
"## cleanup kwargs",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")... | Set up pattern for logging.
name : string
alias for entryname
pattern : string
alias for log_file
conf_file : string
optional path to alternative configuration file
kwargs : boolean|string|int
optional additional flags and parameters
.. note::
``name`` and ``pattern`` were kept for backwards compatibility reasons.
``name`` is an alias for the ``entryname`` argument, ``pattern`` is an alias
for ``log_file``. These aliases will only be used if the ``entryname`` and
``log_file`` arguments are not passed.
For a full list of arguments see ```logadm.show_args```.
CLI Example:
.. code-block:: bash
salt '*' logadm.rotate myapplog pattern='/var/log/myapp/*.log' count=7
salt '*' logadm.rotate myapplog log_file='/var/log/myapp/*.log' count=4 owner=myappd mode='0700' | [
"Set",
"up",
"pattern",
"for",
"logging",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L242-L323 | train |
saltstack/salt | salt/modules/logadm.py | remove | def remove(name, conf_file=default_conf):
'''
Remove log pattern from logadm
CLI Example:
.. code-block:: bash
salt '*' logadm.remove myapplog
'''
command = "logadm -f {0} -r {1}".format(conf_file, name)
result = __salt__['cmd.run_all'](command, python_shell=False)
if result['retcode'] != 0:
return dict(
Error='Failure in removing log. Possibly already removed?',
Output=result['stderr']
)
return dict(Result='Success') | python | def remove(name, conf_file=default_conf):
'''
Remove log pattern from logadm
CLI Example:
.. code-block:: bash
salt '*' logadm.remove myapplog
'''
command = "logadm -f {0} -r {1}".format(conf_file, name)
result = __salt__['cmd.run_all'](command, python_shell=False)
if result['retcode'] != 0:
return dict(
Error='Failure in removing log. Possibly already removed?',
Output=result['stderr']
)
return dict(Result='Success') | [
"def",
"remove",
"(",
"name",
",",
"conf_file",
"=",
"default_conf",
")",
":",
"command",
"=",
"\"logadm -f {0} -r {1}\"",
".",
"format",
"(",
"conf_file",
",",
"name",
")",
"result",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"command",
",",
"python_s... | Remove log pattern from logadm
CLI Example:
.. code-block:: bash
salt '*' logadm.remove myapplog | [
"Remove",
"log",
"pattern",
"from",
"logadm"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L326-L343 | train |
saltstack/salt | salt/utils/locales.py | get_encodings | def get_encodings():
'''
return a list of string encodings to try
'''
encodings = [__salt_system_encoding__]
try:
sys_enc = sys.getdefaultencoding()
except ValueError: # system encoding is nonstandard or malformed
sys_enc = None
if sys_enc and sys_enc not in encodings:
encodings.append(sys_enc)
for enc in ['utf-8', 'latin-1']:
if enc not in encodings:
encodings.append(enc)
return encodings | python | def get_encodings():
'''
return a list of string encodings to try
'''
encodings = [__salt_system_encoding__]
try:
sys_enc = sys.getdefaultencoding()
except ValueError: # system encoding is nonstandard or malformed
sys_enc = None
if sys_enc and sys_enc not in encodings:
encodings.append(sys_enc)
for enc in ['utf-8', 'latin-1']:
if enc not in encodings:
encodings.append(enc)
return encodings | [
"def",
"get_encodings",
"(",
")",
":",
"encodings",
"=",
"[",
"__salt_system_encoding__",
"]",
"try",
":",
"sys_enc",
"=",
"sys",
".",
"getdefaultencoding",
"(",
")",
"except",
"ValueError",
":",
"# system encoding is nonstandard or malformed",
"sys_enc",
"=",
"None... | return a list of string encodings to try | [
"return",
"a",
"list",
"of",
"string",
"encodings",
"to",
"try"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/locales.py#L16-L33 | train |
saltstack/salt | salt/utils/locales.py | split_locale | def split_locale(loc):
'''
Split a locale specifier. The general format is
language[_territory][.codeset][@modifier] [charmap]
For example:
ca_ES.UTF-8@valencia UTF-8
'''
def split(st, char):
'''
Split a string `st` once by `char`; always return a two-element list
even if the second element is empty.
'''
split_st = st.split(char, 1)
if len(split_st) == 1:
split_st.append('')
return split_st
comps = {}
work_st, comps['charmap'] = split(loc, ' ')
work_st, comps['modifier'] = split(work_st, '@')
work_st, comps['codeset'] = split(work_st, '.')
comps['language'], comps['territory'] = split(work_st, '_')
return comps | python | def split_locale(loc):
'''
Split a locale specifier. The general format is
language[_territory][.codeset][@modifier] [charmap]
For example:
ca_ES.UTF-8@valencia UTF-8
'''
def split(st, char):
'''
Split a string `st` once by `char`; always return a two-element list
even if the second element is empty.
'''
split_st = st.split(char, 1)
if len(split_st) == 1:
split_st.append('')
return split_st
comps = {}
work_st, comps['charmap'] = split(loc, ' ')
work_st, comps['modifier'] = split(work_st, '@')
work_st, comps['codeset'] = split(work_st, '.')
comps['language'], comps['territory'] = split(work_st, '_')
return comps | [
"def",
"split_locale",
"(",
"loc",
")",
":",
"def",
"split",
"(",
"st",
",",
"char",
")",
":",
"'''\n Split a string `st` once by `char`; always return a two-element list\n even if the second element is empty.\n '''",
"split_st",
"=",
"st",
".",
"split",
... | Split a locale specifier. The general format is
language[_territory][.codeset][@modifier] [charmap]
For example:
ca_ES.UTF-8@valencia UTF-8 | [
"Split",
"a",
"locale",
"specifier",
".",
"The",
"general",
"format",
"is"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/locales.py#L58-L83 | train |
saltstack/salt | salt/utils/locales.py | join_locale | def join_locale(comps):
'''
Join a locale specifier split in the format returned by split_locale.
'''
loc = comps['language']
if comps.get('territory'):
loc += '_' + comps['territory']
if comps.get('codeset'):
loc += '.' + comps['codeset']
if comps.get('modifier'):
loc += '@' + comps['modifier']
if comps.get('charmap'):
loc += ' ' + comps['charmap']
return loc | python | def join_locale(comps):
'''
Join a locale specifier split in the format returned by split_locale.
'''
loc = comps['language']
if comps.get('territory'):
loc += '_' + comps['territory']
if comps.get('codeset'):
loc += '.' + comps['codeset']
if comps.get('modifier'):
loc += '@' + comps['modifier']
if comps.get('charmap'):
loc += ' ' + comps['charmap']
return loc | [
"def",
"join_locale",
"(",
"comps",
")",
":",
"loc",
"=",
"comps",
"[",
"'language'",
"]",
"if",
"comps",
".",
"get",
"(",
"'territory'",
")",
":",
"loc",
"+=",
"'_'",
"+",
"comps",
"[",
"'territory'",
"]",
"if",
"comps",
".",
"get",
"(",
"'codeset'"... | Join a locale specifier split in the format returned by split_locale. | [
"Join",
"a",
"locale",
"specifier",
"split",
"in",
"the",
"format",
"returned",
"by",
"split_locale",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/locales.py#L86-L99 | train |
saltstack/salt | salt/utils/locales.py | normalize_locale | def normalize_locale(loc):
'''
Format a locale specifier according to the format returned by `locale -a`.
'''
comps = split_locale(loc)
comps['territory'] = comps['territory'].upper()
comps['codeset'] = comps['codeset'].lower().replace('-', '')
comps['charmap'] = ''
return join_locale(comps) | python | def normalize_locale(loc):
'''
Format a locale specifier according to the format returned by `locale -a`.
'''
comps = split_locale(loc)
comps['territory'] = comps['territory'].upper()
comps['codeset'] = comps['codeset'].lower().replace('-', '')
comps['charmap'] = ''
return join_locale(comps) | [
"def",
"normalize_locale",
"(",
"loc",
")",
":",
"comps",
"=",
"split_locale",
"(",
"loc",
")",
"comps",
"[",
"'territory'",
"]",
"=",
"comps",
"[",
"'territory'",
"]",
".",
"upper",
"(",
")",
"comps",
"[",
"'codeset'",
"]",
"=",
"comps",
"[",
"'codese... | Format a locale specifier according to the format returned by `locale -a`. | [
"Format",
"a",
"locale",
"specifier",
"according",
"to",
"the",
"format",
"returned",
"by",
"locale",
"-",
"a",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/locales.py#L102-L110 | train |
saltstack/salt | salt/returners/mongo_return.py | _remove_dots | def _remove_dots(src):
'''
Remove dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output | python | def _remove_dots(src):
'''
Remove dots from the given data structure
'''
output = {}
for key, val in six.iteritems(src):
if isinstance(val, dict):
val = _remove_dots(val)
output[key.replace('.', '-')] = val
return output | [
"def",
"_remove_dots",
"(",
"src",
")",
":",
"output",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"src",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"val",
"=",
"_remove_dots",
"(",
"val",
")... | Remove dots from the given data structure | [
"Remove",
"dots",
"from",
"the",
"given",
"data",
"structure"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_return.py#L96-L105 | train |
saltstack/salt | salt/returners/mongo_return.py | _get_conn | def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
return conn, mdb | python | def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
# at some point we should remove support for
# pymongo versions < 2.3 until then there are
# a bunch of these sections that need to be supported
if PYMONGO_VERSION > _LooseVersion('2.3'):
conn = pymongo.MongoClient(host, port)
else:
conn = pymongo.Connection(host, port)
mdb = conn[db_]
if user and password:
mdb.authenticate(user, password)
if indexes:
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.saltReturns.create_index('minion')
mdb.saltReturns.create_index('jid')
mdb.jobs.create_index('jid')
else:
mdb.saltReturns.ensure_index('minion')
mdb.saltReturns.ensure_index('jid')
mdb.jobs.ensure_index('jid')
return conn, mdb | [
"def",
"_get_conn",
"(",
"ret",
")",
":",
"_options",
"=",
"_get_options",
"(",
"ret",
")",
"host",
"=",
"_options",
".",
"get",
"(",
"'host'",
")",
"port",
"=",
"_options",
".",
"get",
"(",
"'port'",
")",
"db_",
"=",
"_options",
".",
"get",
"(",
"... | Return a mongodb connection object | [
"Return",
"a",
"mongodb",
"connection",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_return.py#L127-L165 | train |
saltstack/salt | salt/returners/mongo_return.py | get_jid | def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret | python | def get_jid(jid):
'''
Return the return information associated with a jid
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0})
if rdata:
for data in rdata:
minion = data['minion']
# return data in the format {<minion>: { <unformatted full return data>}}
ret[minion] = data['full_ret']
return ret | [
"def",
"get_jid",
"(",
"jid",
")",
":",
"conn",
",",
"mdb",
"=",
"_get_conn",
"(",
"ret",
"=",
"None",
")",
"ret",
"=",
"{",
"}",
"rdata",
"=",
"mdb",
".",
"saltReturns",
".",
"find",
"(",
"{",
"'jid'",
":",
"jid",
"}",
",",
"{",
"'_id'",
":",
... | Return the return information associated with a jid | [
"Return",
"the",
"return",
"information",
"associated",
"with",
"a",
"jid"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_return.py#L203-L215 | train |
saltstack/salt | salt/returners/mongo_return.py | get_fun | def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret | python | def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret | [
"def",
"get_fun",
"(",
"fun",
")",
":",
"conn",
",",
"mdb",
"=",
"_get_conn",
"(",
"ret",
"=",
"None",
")",
"ret",
"=",
"{",
"}",
"rdata",
"=",
"mdb",
".",
"saltReturns",
".",
"find_one",
"(",
"{",
"'fun'",
":",
"fun",
"}",
",",
"{",
"'_id'",
"... | Return the most recent jobs that have executed the named function | [
"Return",
"the",
"most",
"recent",
"jobs",
"that",
"have",
"executed",
"the",
"named",
"function"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_return.py#L218-L227 | train |
saltstack/salt | salt/modules/acme.py | _cert_file | def _cert_file(name, cert_type):
'''
Return expected path of a Let's Encrypt live cert
'''
return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type)) | python | def _cert_file(name, cert_type):
'''
Return expected path of a Let's Encrypt live cert
'''
return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type)) | [
"def",
"_cert_file",
"(",
"name",
",",
"cert_type",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"LE_LIVE",
",",
"name",
",",
"'{0}.pem'",
".",
"format",
"(",
"cert_type",
")",
")"
] | Return expected path of a Let's Encrypt live cert | [
"Return",
"expected",
"path",
"of",
"a",
"Let",
"s",
"Encrypt",
"live",
"cert"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L64-L68 | train |
saltstack/salt | salt/modules/acme.py | _expires | def _expires(name):
'''
Return the expiry date of a cert
:return datetime object of expiry date
'''
cert_file = _cert_file(name, 'cert')
# Use the salt module if available
if 'tls.cert_info' in __salt__:
expiry = __salt__['tls.cert_info'](cert_file)['not_after']
# Cobble it together using the openssl binary
else:
openssl_cmd = 'openssl x509 -in {0} -noout -enddate'.format(cert_file)
# No %e format on my Linux'es here
strptime_sux_cmd = 'date --date="$({0} | cut -d= -f2)" +%s'.format(openssl_cmd)
expiry = float(__salt__['cmd.shell'](strptime_sux_cmd, output_loglevel='quiet'))
# expiry = datetime.datetime.strptime(expiry.split('=', 1)[-1], '%b %e %H:%M:%S %Y %Z')
return datetime.datetime.fromtimestamp(expiry) | python | def _expires(name):
'''
Return the expiry date of a cert
:return datetime object of expiry date
'''
cert_file = _cert_file(name, 'cert')
# Use the salt module if available
if 'tls.cert_info' in __salt__:
expiry = __salt__['tls.cert_info'](cert_file)['not_after']
# Cobble it together using the openssl binary
else:
openssl_cmd = 'openssl x509 -in {0} -noout -enddate'.format(cert_file)
# No %e format on my Linux'es here
strptime_sux_cmd = 'date --date="$({0} | cut -d= -f2)" +%s'.format(openssl_cmd)
expiry = float(__salt__['cmd.shell'](strptime_sux_cmd, output_loglevel='quiet'))
# expiry = datetime.datetime.strptime(expiry.split('=', 1)[-1], '%b %e %H:%M:%S %Y %Z')
return datetime.datetime.fromtimestamp(expiry) | [
"def",
"_expires",
"(",
"name",
")",
":",
"cert_file",
"=",
"_cert_file",
"(",
"name",
",",
"'cert'",
")",
"# Use the salt module if available",
"if",
"'tls.cert_info'",
"in",
"__salt__",
":",
"expiry",
"=",
"__salt__",
"[",
"'tls.cert_info'",
"]",
"(",
"cert_fi... | Return the expiry date of a cert
:return datetime object of expiry date | [
"Return",
"the",
"expiry",
"date",
"of",
"a",
"cert"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L71-L89 | train |
saltstack/salt | salt/modules/acme.py | _renew_by | def _renew_by(name, window=None):
'''
Date before a certificate should be renewed
:param name: Common Name of the certificate (DNS name of certificate)
:param window: days before expiry date to renew
:return datetime object of first renewal date
'''
expiry = _expires(name)
if window is not None:
expiry = expiry - datetime.timedelta(days=window)
return expiry | python | def _renew_by(name, window=None):
'''
Date before a certificate should be renewed
:param name: Common Name of the certificate (DNS name of certificate)
:param window: days before expiry date to renew
:return datetime object of first renewal date
'''
expiry = _expires(name)
if window is not None:
expiry = expiry - datetime.timedelta(days=window)
return expiry | [
"def",
"_renew_by",
"(",
"name",
",",
"window",
"=",
"None",
")",
":",
"expiry",
"=",
"_expires",
"(",
"name",
")",
"if",
"window",
"is",
"not",
"None",
":",
"expiry",
"=",
"expiry",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"window",
")",... | Date before a certificate should be renewed
:param name: Common Name of the certificate (DNS name of certificate)
:param window: days before expiry date to renew
:return datetime object of first renewal date | [
"Date",
"before",
"a",
"certificate",
"should",
"be",
"renewed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L92-L104 | train |
saltstack/salt | salt/modules/acme.py | cert | def cert(name,
aliases=None,
email=None,
webroot=None,
test_cert=False,
renew=None,
keysize=None,
server=None,
owner='root',
group='root',
mode='0640',
certname=None,
preferred_challenges=None,
tls_sni_01_port=None,
tls_sni_01_address=None,
http_01_port=None,
http_01_address=None,
dns_plugin=None,
dns_plugin_credentials=None,
dns_plugin_propagate_seconds=10):
'''
Obtain/renew a certificate from an ACME CA, probably Let's Encrypt.
:param name: Common Name of the certificate (DNS name of certificate)
:param aliases: subjectAltNames (Additional DNS names on certificate)
:param email: e-mail address for interaction with ACME provider
:param webroot: True or a full path to use to use webroot. Otherwise use standalone mode
:param test_cert: Request a certificate from the Happy Hacker Fake CA (mutually exclusive with 'server')
:param renew: True/'force' to force a renewal, or a window of renewal before expiry in days
:param keysize: RSA key bits
:param server: API endpoint to talk to
:param owner: owner of the private key file
:param group: group of the private key file
:param mode: mode of the private key file
:param certname: Name of the certificate to save
:param preferred_challenges: A sorted, comma delimited list of the preferred
challenge to use during authorization with the
most preferred challenge listed first.
:param tls_sni_01_port: Port used during tls-sni-01 challenge. This only affects
the port Certbot listens on. A conforming ACME server
will still attempt to connect on port 443.
:param tls_sni_01_address: The address the server listens to during tls-sni-01
challenge.
:param http_01_port: Port used in the http-01 challenge. This only affects
the port Certbot listens on. A conforming ACME server
will still attempt to connect on port 80.
:param https_01_address: The address the server listens to during http-01 challenge.
:param dns_plugin: Name of a DNS plugin to use (currently only 'cloudflare' or 'digitalocean')
:param dns_plugin_credentials: Path to the credentials file if required by the specified DNS plugin
:param dns_plugin_propagate_seconds: Number of seconds to wait for DNS propogations before
asking ACME servers to verify the DNS record. (default 10)
:return: dict with 'result' True/False/None, 'comment' and certificate's expiry date ('not_after')
CLI example:
.. code-block:: bash
salt 'gitlab.example.com' acme.cert dev.example.com "[gitlab.example.com]" test_cert=True renew=14 webroot=/opt/gitlab/embedded/service/gitlab-rails/public
'''
cmd = [LEA, 'certonly', '--non-interactive', '--agree-tos']
supported_dns_plugins = ['cloudflare', 'digitalocean']
cert_file = _cert_file(name, 'cert')
if not __salt__['file.file_exists'](cert_file):
log.debug('Certificate %s does not exist (yet)', cert_file)
renew = False
elif needs_renewal(name, renew):
log.debug('Certificate %s will be renewed', cert_file)
cmd.append('--renew-by-default')
renew = True
if server:
cmd.append('--server {0}'.format(server))
if certname:
cmd.append('--cert-name {0}'.format(certname))
if test_cert:
if server:
return {'result': False, 'comment': 'Use either server or test_cert, not both'}
cmd.append('--test-cert')
if webroot:
cmd.append('--authenticator webroot')
if webroot is not True:
cmd.append('--webroot-path {0}'.format(webroot))
elif dns_plugin in supported_dns_plugins:
if dns_plugin == 'cloudflare':
cmd.append('--dns-cloudflare')
cmd.append('--dns-cloudflare-credentials {0}'.format(dns_plugin_credentials))
cmd.append('--dns-cloudflare-propagation-seconds {0}'.format(dns_plugin_propagate_seconds))
elif dns_plugin == 'digitalocean':
cmd.append('--dns-digitalocean')
cmd.append('--dns-digitalocean-credentials {0}'.format(dns_plugin_credentials))
cmd.append('--dns-digitalocean-propagation-seconds {0}'.format(dns_plugin_propagate_seconds))
else:
return {'result': False, 'comment': 'DNS plugin \'{0}\' is not supported'.format(dns_plugin)}
else:
cmd.append('--authenticator standalone')
if email:
cmd.append('--email {0}'.format(email))
if keysize:
cmd.append('--rsa-key-size {0}'.format(keysize))
cmd.append('--domains {0}'.format(name))
if aliases is not None:
for dns in aliases:
cmd.append('--domains {0}'.format(dns))
if preferred_challenges:
cmd.append('--preferred-challenges {}'.format(preferred_challenges))
if tls_sni_01_port:
cmd.append('--tls-sni-01-port {}'.format(tls_sni_01_port))
if tls_sni_01_address:
cmd.append('--tls-sni-01-address {}'.format(tls_sni_01_address))
if http_01_port:
cmd.append('--http-01-port {}'.format(http_01_port))
if http_01_address:
cmd.append('--http-01-address {}'.format(http_01_address))
res = __salt__['cmd.run_all'](' '.join(cmd))
if res['retcode'] != 0:
if 'expand' in res['stderr']:
cmd.append('--expand')
res = __salt__['cmd.run_all'](' '.join(cmd))
if res['retcode'] != 0:
return {'result': False, 'comment': 'Certificate {0} renewal failed with:\n{1}'.format(name, res['stderr'])}
else:
return {'result': False, 'comment': 'Certificate {0} renewal failed with:\n{1}'.format(name, res['stderr'])}
if 'no action taken' in res['stdout']:
comment = 'Certificate {0} unchanged'.format(cert_file)
result = None
elif renew:
comment = 'Certificate {0} renewed'.format(name)
result = True
else:
comment = 'Certificate {0} obtained'.format(name)
result = True
ret = {'comment': comment, 'not_after': expires(name), 'changes': {}, 'result': result}
ret, _ = __salt__['file.check_perms'](_cert_file(name, 'privkey'),
ret,
owner, group, mode,
follow_symlinks=True)
return ret | python | def cert(name,
aliases=None,
email=None,
webroot=None,
test_cert=False,
renew=None,
keysize=None,
server=None,
owner='root',
group='root',
mode='0640',
certname=None,
preferred_challenges=None,
tls_sni_01_port=None,
tls_sni_01_address=None,
http_01_port=None,
http_01_address=None,
dns_plugin=None,
dns_plugin_credentials=None,
dns_plugin_propagate_seconds=10):
'''
Obtain/renew a certificate from an ACME CA, probably Let's Encrypt.
:param name: Common Name of the certificate (DNS name of certificate)
:param aliases: subjectAltNames (Additional DNS names on certificate)
:param email: e-mail address for interaction with ACME provider
:param webroot: True or a full path to use to use webroot. Otherwise use standalone mode
:param test_cert: Request a certificate from the Happy Hacker Fake CA (mutually exclusive with 'server')
:param renew: True/'force' to force a renewal, or a window of renewal before expiry in days
:param keysize: RSA key bits
:param server: API endpoint to talk to
:param owner: owner of the private key file
:param group: group of the private key file
:param mode: mode of the private key file
:param certname: Name of the certificate to save
:param preferred_challenges: A sorted, comma delimited list of the preferred
challenge to use during authorization with the
most preferred challenge listed first.
:param tls_sni_01_port: Port used during tls-sni-01 challenge. This only affects
the port Certbot listens on. A conforming ACME server
will still attempt to connect on port 443.
:param tls_sni_01_address: The address the server listens to during tls-sni-01
challenge.
:param http_01_port: Port used in the http-01 challenge. This only affects
the port Certbot listens on. A conforming ACME server
will still attempt to connect on port 80.
:param https_01_address: The address the server listens to during http-01 challenge.
:param dns_plugin: Name of a DNS plugin to use (currently only 'cloudflare' or 'digitalocean')
:param dns_plugin_credentials: Path to the credentials file if required by the specified DNS plugin
:param dns_plugin_propagate_seconds: Number of seconds to wait for DNS propogations before
asking ACME servers to verify the DNS record. (default 10)
:return: dict with 'result' True/False/None, 'comment' and certificate's expiry date ('not_after')
CLI example:
.. code-block:: bash
salt 'gitlab.example.com' acme.cert dev.example.com "[gitlab.example.com]" test_cert=True renew=14 webroot=/opt/gitlab/embedded/service/gitlab-rails/public
'''
cmd = [LEA, 'certonly', '--non-interactive', '--agree-tos']
supported_dns_plugins = ['cloudflare', 'digitalocean']
cert_file = _cert_file(name, 'cert')
if not __salt__['file.file_exists'](cert_file):
log.debug('Certificate %s does not exist (yet)', cert_file)
renew = False
elif needs_renewal(name, renew):
log.debug('Certificate %s will be renewed', cert_file)
cmd.append('--renew-by-default')
renew = True
if server:
cmd.append('--server {0}'.format(server))
if certname:
cmd.append('--cert-name {0}'.format(certname))
if test_cert:
if server:
return {'result': False, 'comment': 'Use either server or test_cert, not both'}
cmd.append('--test-cert')
if webroot:
cmd.append('--authenticator webroot')
if webroot is not True:
cmd.append('--webroot-path {0}'.format(webroot))
elif dns_plugin in supported_dns_plugins:
if dns_plugin == 'cloudflare':
cmd.append('--dns-cloudflare')
cmd.append('--dns-cloudflare-credentials {0}'.format(dns_plugin_credentials))
cmd.append('--dns-cloudflare-propagation-seconds {0}'.format(dns_plugin_propagate_seconds))
elif dns_plugin == 'digitalocean':
cmd.append('--dns-digitalocean')
cmd.append('--dns-digitalocean-credentials {0}'.format(dns_plugin_credentials))
cmd.append('--dns-digitalocean-propagation-seconds {0}'.format(dns_plugin_propagate_seconds))
else:
return {'result': False, 'comment': 'DNS plugin \'{0}\' is not supported'.format(dns_plugin)}
else:
cmd.append('--authenticator standalone')
if email:
cmd.append('--email {0}'.format(email))
if keysize:
cmd.append('--rsa-key-size {0}'.format(keysize))
cmd.append('--domains {0}'.format(name))
if aliases is not None:
for dns in aliases:
cmd.append('--domains {0}'.format(dns))
if preferred_challenges:
cmd.append('--preferred-challenges {}'.format(preferred_challenges))
if tls_sni_01_port:
cmd.append('--tls-sni-01-port {}'.format(tls_sni_01_port))
if tls_sni_01_address:
cmd.append('--tls-sni-01-address {}'.format(tls_sni_01_address))
if http_01_port:
cmd.append('--http-01-port {}'.format(http_01_port))
if http_01_address:
cmd.append('--http-01-address {}'.format(http_01_address))
res = __salt__['cmd.run_all'](' '.join(cmd))
if res['retcode'] != 0:
if 'expand' in res['stderr']:
cmd.append('--expand')
res = __salt__['cmd.run_all'](' '.join(cmd))
if res['retcode'] != 0:
return {'result': False, 'comment': 'Certificate {0} renewal failed with:\n{1}'.format(name, res['stderr'])}
else:
return {'result': False, 'comment': 'Certificate {0} renewal failed with:\n{1}'.format(name, res['stderr'])}
if 'no action taken' in res['stdout']:
comment = 'Certificate {0} unchanged'.format(cert_file)
result = None
elif renew:
comment = 'Certificate {0} renewed'.format(name)
result = True
else:
comment = 'Certificate {0} obtained'.format(name)
result = True
ret = {'comment': comment, 'not_after': expires(name), 'changes': {}, 'result': result}
ret, _ = __salt__['file.check_perms'](_cert_file(name, 'privkey'),
ret,
owner, group, mode,
follow_symlinks=True)
return ret | [
"def",
"cert",
"(",
"name",
",",
"aliases",
"=",
"None",
",",
"email",
"=",
"None",
",",
"webroot",
"=",
"None",
",",
"test_cert",
"=",
"False",
",",
"renew",
"=",
"None",
",",
"keysize",
"=",
"None",
",",
"server",
"=",
"None",
",",
"owner",
"=",
... | Obtain/renew a certificate from an ACME CA, probably Let's Encrypt.
:param name: Common Name of the certificate (DNS name of certificate)
:param aliases: subjectAltNames (Additional DNS names on certificate)
:param email: e-mail address for interaction with ACME provider
:param webroot: True or a full path to use to use webroot. Otherwise use standalone mode
:param test_cert: Request a certificate from the Happy Hacker Fake CA (mutually exclusive with 'server')
:param renew: True/'force' to force a renewal, or a window of renewal before expiry in days
:param keysize: RSA key bits
:param server: API endpoint to talk to
:param owner: owner of the private key file
:param group: group of the private key file
:param mode: mode of the private key file
:param certname: Name of the certificate to save
:param preferred_challenges: A sorted, comma delimited list of the preferred
challenge to use during authorization with the
most preferred challenge listed first.
:param tls_sni_01_port: Port used during tls-sni-01 challenge. This only affects
the port Certbot listens on. A conforming ACME server
will still attempt to connect on port 443.
:param tls_sni_01_address: The address the server listens to during tls-sni-01
challenge.
:param http_01_port: Port used in the http-01 challenge. This only affects
the port Certbot listens on. A conforming ACME server
will still attempt to connect on port 80.
:param https_01_address: The address the server listens to during http-01 challenge.
:param dns_plugin: Name of a DNS plugin to use (currently only 'cloudflare' or 'digitalocean')
:param dns_plugin_credentials: Path to the credentials file if required by the specified DNS plugin
:param dns_plugin_propagate_seconds: Number of seconds to wait for DNS propogations before
asking ACME servers to verify the DNS record. (default 10)
:return: dict with 'result' True/False/None, 'comment' and certificate's expiry date ('not_after')
CLI example:
.. code-block:: bash
salt 'gitlab.example.com' acme.cert dev.example.com "[gitlab.example.com]" test_cert=True renew=14 webroot=/opt/gitlab/embedded/service/gitlab-rails/public | [
"Obtain",
"/",
"renew",
"a",
"certificate",
"from",
"an",
"ACME",
"CA",
"probably",
"Let",
"s",
"Encrypt",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L107-L258 | train |
saltstack/salt | salt/modules/acme.py | info | def info(name):
'''
Return information about a certificate
.. note::
Will output tls.cert_info if that's available, or OpenSSL text if not
:param name: CommonName of cert
CLI example:
.. code-block:: bash
salt 'gitlab.example.com' acme.info dev.example.com
'''
cert_file = _cert_file(name, 'cert')
# Use the salt module if available
if 'tls.cert_info' in __salt__:
cert_info = __salt__['tls.cert_info'](cert_file)
# Strip out the extensions object contents;
# these trip over our poor state output
# and they serve no real purpose here anyway
cert_info['extensions'] = cert_info['extensions'].keys()
return cert_info
# Cobble it together using the openssl binary
openssl_cmd = 'openssl x509 -in {0} -noout -text'.format(cert_file)
return __salt__['cmd.run'](openssl_cmd, output_loglevel='quiet') | python | def info(name):
'''
Return information about a certificate
.. note::
Will output tls.cert_info if that's available, or OpenSSL text if not
:param name: CommonName of cert
CLI example:
.. code-block:: bash
salt 'gitlab.example.com' acme.info dev.example.com
'''
cert_file = _cert_file(name, 'cert')
# Use the salt module if available
if 'tls.cert_info' in __salt__:
cert_info = __salt__['tls.cert_info'](cert_file)
# Strip out the extensions object contents;
# these trip over our poor state output
# and they serve no real purpose here anyway
cert_info['extensions'] = cert_info['extensions'].keys()
return cert_info
# Cobble it together using the openssl binary
openssl_cmd = 'openssl x509 -in {0} -noout -text'.format(cert_file)
return __salt__['cmd.run'](openssl_cmd, output_loglevel='quiet') | [
"def",
"info",
"(",
"name",
")",
":",
"cert_file",
"=",
"_cert_file",
"(",
"name",
",",
"'cert'",
")",
"# Use the salt module if available",
"if",
"'tls.cert_info'",
"in",
"__salt__",
":",
"cert_info",
"=",
"__salt__",
"[",
"'tls.cert_info'",
"]",
"(",
"cert_fil... | Return information about a certificate
.. note::
Will output tls.cert_info if that's available, or OpenSSL text if not
:param name: CommonName of cert
CLI example:
.. code-block:: bash
salt 'gitlab.example.com' acme.info dev.example.com | [
"Return",
"information",
"about",
"a",
"certificate"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L274-L300 | train |
saltstack/salt | salt/modules/acme.py | needs_renewal | def needs_renewal(name, window=None):
'''
Check if a certificate needs renewal
:param name: CommonName of cert
:param window: Window in days to renew earlier or True/force to just return True
Code example:
.. code-block:: python
if __salt__['acme.needs_renewal']('dev.example.com'):
__salt__['acme.cert']('dev.example.com', **kwargs)
else:
log.info('Your certificate is still good')
'''
if window is not None and window in ('force', 'Force', True):
return True
return _renew_by(name, window) <= datetime.datetime.today() | python | def needs_renewal(name, window=None):
'''
Check if a certificate needs renewal
:param name: CommonName of cert
:param window: Window in days to renew earlier or True/force to just return True
Code example:
.. code-block:: python
if __salt__['acme.needs_renewal']('dev.example.com'):
__salt__['acme.cert']('dev.example.com', **kwargs)
else:
log.info('Your certificate is still good')
'''
if window is not None and window in ('force', 'Force', True):
return True
return _renew_by(name, window) <= datetime.datetime.today() | [
"def",
"needs_renewal",
"(",
"name",
",",
"window",
"=",
"None",
")",
":",
"if",
"window",
"is",
"not",
"None",
"and",
"window",
"in",
"(",
"'force'",
",",
"'Force'",
",",
"True",
")",
":",
"return",
"True",
"return",
"_renew_by",
"(",
"name",
",",
"... | Check if a certificate needs renewal
:param name: CommonName of cert
:param window: Window in days to renew earlier or True/force to just return True
Code example:
.. code-block:: python
if __salt__['acme.needs_renewal']('dev.example.com'):
__salt__['acme.cert']('dev.example.com', **kwargs)
else:
log.info('Your certificate is still good') | [
"Check",
"if",
"a",
"certificate",
"needs",
"renewal"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L344-L363 | train |
saltstack/salt | salt/modules/drbd.py | _analyse_overview_field | def _analyse_overview_field(content):
'''
Split the field in drbd-overview
'''
if "(" in content:
# Output like "Connected(2*)" or "UpToDate(2*)"
return content.split("(")[0], content.split("(")[0]
elif "/" in content:
# Output like "Primar/Second" or "UpToDa/UpToDa"
return content.split("/")[0], content.split("/")[1]
return content, "" | python | def _analyse_overview_field(content):
'''
Split the field in drbd-overview
'''
if "(" in content:
# Output like "Connected(2*)" or "UpToDate(2*)"
return content.split("(")[0], content.split("(")[0]
elif "/" in content:
# Output like "Primar/Second" or "UpToDa/UpToDa"
return content.split("/")[0], content.split("/")[1]
return content, "" | [
"def",
"_analyse_overview_field",
"(",
"content",
")",
":",
"if",
"\"(\"",
"in",
"content",
":",
"# Output like \"Connected(2*)\" or \"UpToDate(2*)\"",
"return",
"content",
".",
"split",
"(",
"\"(\"",
")",
"[",
"0",
"]",
",",
"content",
".",
"split",
"(",
"\"(\"... | Split the field in drbd-overview | [
"Split",
"the",
"field",
"in",
"drbd",
"-",
"overview"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L13-L24 | train |
saltstack/salt | salt/modules/drbd.py | _count_spaces_startswith | def _count_spaces_startswith(line):
'''
Count the number of spaces before the first character
'''
if line.split('#')[0].strip() == "":
return None
spaces = 0
for i in line:
if i.isspace():
spaces += 1
else:
return spaces | python | def _count_spaces_startswith(line):
'''
Count the number of spaces before the first character
'''
if line.split('#')[0].strip() == "":
return None
spaces = 0
for i in line:
if i.isspace():
spaces += 1
else:
return spaces | [
"def",
"_count_spaces_startswith",
"(",
"line",
")",
":",
"if",
"line",
".",
"split",
"(",
"'#'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"==",
"\"\"",
":",
"return",
"None",
"spaces",
"=",
"0",
"for",
"i",
"in",
"line",
":",
"if",
"i",
".",
... | Count the number of spaces before the first character | [
"Count",
"the",
"number",
"of",
"spaces",
"before",
"the",
"first",
"character"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L27-L39 | train |
saltstack/salt | salt/modules/drbd.py | _analyse_status_type | def _analyse_status_type(line):
'''
Figure out the sections in drbdadm status
'''
spaces = _count_spaces_startswith(line)
if spaces is None:
return ''
switch = {
0: 'RESOURCE',
2: {' disk:': 'LOCALDISK', ' role:': 'PEERNODE', ' connection:': 'PEERNODE'},
4: {' peer-disk:': 'PEERDISK'}
}
ret = switch.get(spaces, 'UNKNOWN')
# isinstance(ret, str) only works when run directly, calling need unicode(six)
if isinstance(ret, six.text_type):
return ret
for x in ret:
if x in line:
return ret[x]
return 'UNKNOWN' | python | def _analyse_status_type(line):
'''
Figure out the sections in drbdadm status
'''
spaces = _count_spaces_startswith(line)
if spaces is None:
return ''
switch = {
0: 'RESOURCE',
2: {' disk:': 'LOCALDISK', ' role:': 'PEERNODE', ' connection:': 'PEERNODE'},
4: {' peer-disk:': 'PEERDISK'}
}
ret = switch.get(spaces, 'UNKNOWN')
# isinstance(ret, str) only works when run directly, calling need unicode(six)
if isinstance(ret, six.text_type):
return ret
for x in ret:
if x in line:
return ret[x]
return 'UNKNOWN' | [
"def",
"_analyse_status_type",
"(",
"line",
")",
":",
"spaces",
"=",
"_count_spaces_startswith",
"(",
"line",
")",
"if",
"spaces",
"is",
"None",
":",
"return",
"''",
"switch",
"=",
"{",
"0",
":",
"'RESOURCE'",
",",
"2",
":",
"{",
"' disk:'",
":",
"'LOCAL... | Figure out the sections in drbdadm status | [
"Figure",
"out",
"the",
"sections",
"in",
"drbdadm",
"status"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L42-L67 | train |
saltstack/salt | salt/modules/drbd.py | _add_res | def _add_res(line):
'''
Analyse the line of local resource of ``drbdadm status``
'''
global resource
fields = line.strip().split()
if resource:
ret.append(resource)
resource = {}
resource["resource name"] = fields[0]
resource["local role"] = fields[1].split(":")[1]
resource["local volumes"] = []
resource["peer nodes"] = [] | python | def _add_res(line):
'''
Analyse the line of local resource of ``drbdadm status``
'''
global resource
fields = line.strip().split()
if resource:
ret.append(resource)
resource = {}
resource["resource name"] = fields[0]
resource["local role"] = fields[1].split(":")[1]
resource["local volumes"] = []
resource["peer nodes"] = [] | [
"def",
"_add_res",
"(",
"line",
")",
":",
"global",
"resource",
"fields",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"if",
"resource",
":",
"ret",
".",
"append",
"(",
"resource",
")",
"resource",
"=",
"{",
"}",
"resource",
"[",
"\... | Analyse the line of local resource of ``drbdadm status`` | [
"Analyse",
"the",
"line",
"of",
"local",
"resource",
"of",
"drbdadm",
"status"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L70-L84 | train |
saltstack/salt | salt/modules/drbd.py | _add_volume | def _add_volume(line):
'''
Analyse the line of volumes of ``drbdadm status``
'''
section = _analyse_status_type(line)
fields = line.strip().split()
volume = {}
for field in fields:
volume[field.split(':')[0]] = field.split(':')[1]
if section == 'LOCALDISK':
resource['local volumes'].append(volume)
else:
# 'PEERDISK'
lastpnodevolumes.append(volume) | python | def _add_volume(line):
'''
Analyse the line of volumes of ``drbdadm status``
'''
section = _analyse_status_type(line)
fields = line.strip().split()
volume = {}
for field in fields:
volume[field.split(':')[0]] = field.split(':')[1]
if section == 'LOCALDISK':
resource['local volumes'].append(volume)
else:
# 'PEERDISK'
lastpnodevolumes.append(volume) | [
"def",
"_add_volume",
"(",
"line",
")",
":",
"section",
"=",
"_analyse_status_type",
"(",
"line",
")",
"fields",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"volume",
"=",
"{",
"}",
"for",
"field",
"in",
"fields",
":",
"volume",
"[",... | Analyse the line of volumes of ``drbdadm status`` | [
"Analyse",
"the",
"line",
"of",
"volumes",
"of",
"drbdadm",
"status"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L87-L102 | train |
saltstack/salt | salt/modules/drbd.py | _add_peernode | def _add_peernode(line):
'''
Analyse the line of peer nodes of ``drbdadm status``
'''
global lastpnodevolumes
fields = line.strip().split()
peernode = {}
peernode["peernode name"] = fields[0]
#Could be role or connection:
peernode[fields[1].split(":")[0]] = fields[1].split(":")[1]
peernode["peer volumes"] = []
resource["peer nodes"].append(peernode)
lastpnodevolumes = peernode["peer volumes"] | python | def _add_peernode(line):
'''
Analyse the line of peer nodes of ``drbdadm status``
'''
global lastpnodevolumes
fields = line.strip().split()
peernode = {}
peernode["peernode name"] = fields[0]
#Could be role or connection:
peernode[fields[1].split(":")[0]] = fields[1].split(":")[1]
peernode["peer volumes"] = []
resource["peer nodes"].append(peernode)
lastpnodevolumes = peernode["peer volumes"] | [
"def",
"_add_peernode",
"(",
"line",
")",
":",
"global",
"lastpnodevolumes",
"fields",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"peernode",
"=",
"{",
"}",
"peernode",
"[",
"\"peernode name\"",
"]",
"=",
"fields",
"[",
"0",
"]",
"#Co... | Analyse the line of peer nodes of ``drbdadm status`` | [
"Analyse",
"the",
"line",
"of",
"peer",
"nodes",
"of",
"drbdadm",
"status"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L105-L119 | train |
saltstack/salt | salt/modules/drbd.py | _line_parser | def _line_parser(line):
'''
Call action for different lines
'''
section = _analyse_status_type(line)
fields = line.strip().split()
switch = {
'': _empty,
'RESOURCE': _add_res,
'PEERNODE': _add_peernode,
'LOCALDISK': _add_volume,
'PEERDISK': _add_volume,
}
func = switch.get(section, _unknown_parser)
func(line) | python | def _line_parser(line):
'''
Call action for different lines
'''
section = _analyse_status_type(line)
fields = line.strip().split()
switch = {
'': _empty,
'RESOURCE': _add_res,
'PEERNODE': _add_peernode,
'LOCALDISK': _add_volume,
'PEERDISK': _add_volume,
}
func = switch.get(section, _unknown_parser)
func(line) | [
"def",
"_line_parser",
"(",
"line",
")",
":",
"section",
"=",
"_analyse_status_type",
"(",
"line",
")",
"fields",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"switch",
"=",
"{",
"''",
":",
"_empty",
",",
"'RESOURCE'",
":",
"_add_res",
... | Call action for different lines | [
"Call",
"action",
"for",
"different",
"lines"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L137-L154 | train |
saltstack/salt | salt/modules/drbd.py | overview | def overview():
'''
Show status of the DRBD devices, support two nodes only.
drbd-overview is removed since drbd-utils-9.6.0,
use status instead.
CLI Example:
.. code-block:: bash
salt '*' drbd.overview
'''
cmd = 'drbd-overview'
for line in __salt__['cmd.run'](cmd).splitlines():
ret = {}
fields = line.strip().split()
minnum = fields[0].split(':')[0]
device = fields[0].split(':')[1]
connstate, _ = _analyse_overview_field(fields[1])
localrole, partnerrole = _analyse_overview_field(fields[2])
localdiskstate, partnerdiskstate = _analyse_overview_field(fields[3])
if localdiskstate.startswith("UpTo"):
if partnerdiskstate.startswith("UpTo"):
if len(fields) >= 5:
mountpoint = fields[4]
fs_mounted = fields[5]
totalsize = fields[6]
usedsize = fields[7]
remainsize = fields[8]
perc = fields[9]
ret = {
'minor number': minnum,
'device': device,
'connection state': connstate,
'local role': localrole,
'partner role': partnerrole,
'local disk state': localdiskstate,
'partner disk state': partnerdiskstate,
'mountpoint': mountpoint,
'fs': fs_mounted,
'total size': totalsize,
'used': usedsize,
'remains': remainsize,
'percent': perc,
}
else:
ret = {
'minor number': minnum,
'device': device,
'connection state': connstate,
'local role': localrole,
'partner role': partnerrole,
'local disk state': localdiskstate,
'partner disk state': partnerdiskstate,
}
else:
syncbar = fields[4]
synced = fields[6]
syncedbytes = fields[7]
sync = synced+syncedbytes
ret = {
'minor number': minnum,
'device': device,
'connection state': connstate,
'local role': localrole,
'partner role': partnerrole,
'local disk state': localdiskstate,
'partner disk state': partnerdiskstate,
'synchronisation: ': syncbar,
'synched': sync,
}
return ret | python | def overview():
'''
Show status of the DRBD devices, support two nodes only.
drbd-overview is removed since drbd-utils-9.6.0,
use status instead.
CLI Example:
.. code-block:: bash
salt '*' drbd.overview
'''
cmd = 'drbd-overview'
for line in __salt__['cmd.run'](cmd).splitlines():
ret = {}
fields = line.strip().split()
minnum = fields[0].split(':')[0]
device = fields[0].split(':')[1]
connstate, _ = _analyse_overview_field(fields[1])
localrole, partnerrole = _analyse_overview_field(fields[2])
localdiskstate, partnerdiskstate = _analyse_overview_field(fields[3])
if localdiskstate.startswith("UpTo"):
if partnerdiskstate.startswith("UpTo"):
if len(fields) >= 5:
mountpoint = fields[4]
fs_mounted = fields[5]
totalsize = fields[6]
usedsize = fields[7]
remainsize = fields[8]
perc = fields[9]
ret = {
'minor number': minnum,
'device': device,
'connection state': connstate,
'local role': localrole,
'partner role': partnerrole,
'local disk state': localdiskstate,
'partner disk state': partnerdiskstate,
'mountpoint': mountpoint,
'fs': fs_mounted,
'total size': totalsize,
'used': usedsize,
'remains': remainsize,
'percent': perc,
}
else:
ret = {
'minor number': minnum,
'device': device,
'connection state': connstate,
'local role': localrole,
'partner role': partnerrole,
'local disk state': localdiskstate,
'partner disk state': partnerdiskstate,
}
else:
syncbar = fields[4]
synced = fields[6]
syncedbytes = fields[7]
sync = synced+syncedbytes
ret = {
'minor number': minnum,
'device': device,
'connection state': connstate,
'local role': localrole,
'partner role': partnerrole,
'local disk state': localdiskstate,
'partner disk state': partnerdiskstate,
'synchronisation: ': syncbar,
'synched': sync,
}
return ret | [
"def",
"overview",
"(",
")",
":",
"cmd",
"=",
"'drbd-overview'",
"for",
"line",
"in",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"fields",
"=",
"line",
".",
"strip",
"(",
")",
".",
... | Show status of the DRBD devices, support two nodes only.
drbd-overview is removed since drbd-utils-9.6.0,
use status instead.
CLI Example:
.. code-block:: bash
salt '*' drbd.overview | [
"Show",
"status",
"of",
"the",
"DRBD",
"devices",
"support",
"two",
"nodes",
"only",
".",
"drbd",
"-",
"overview",
"is",
"removed",
"since",
"drbd",
"-",
"utils",
"-",
"9",
".",
"6",
".",
"0",
"use",
"status",
"instead",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L157-L228 | train |
saltstack/salt | salt/modules/drbd.py | status | def status(name='all'):
'''
Using drbdadm to show status of the DRBD devices,
available in the latest drbd9.
Support multiple nodes, multiple volumes.
:type name: str
:param name:
Resource name.
:return: drbd status of resource.
:rtype: list(dict(res))
CLI Example:
.. code-block:: bash
salt '*' drbd.status
salt '*' drbd.status name=<resource name>
'''
# Initialize for multiple times test cases
global ret
global resource
ret = []
resource = {}
cmd = ['drbdadm', 'status']
cmd.append(name)
#One possible output: (number of resource/node/vol are flexible)
#resource role:Secondary
# volume:0 disk:Inconsistent
# volume:1 disk:Inconsistent
# drbd-node1 role:Primary
# volume:0 replication:SyncTarget peer-disk:UpToDate done:10.17
# volume:1 replication:SyncTarget peer-disk:UpToDate done:74.08
# drbd-node2 role:Secondary
# volume:0 peer-disk:Inconsistent resync-suspended:peer
# volume:1 peer-disk:Inconsistent resync-suspended:peer
for line in __salt__['cmd.run'](cmd).splitlines():
_line_parser(line)
if resource:
ret.append(resource)
return ret | python | def status(name='all'):
'''
Using drbdadm to show status of the DRBD devices,
available in the latest drbd9.
Support multiple nodes, multiple volumes.
:type name: str
:param name:
Resource name.
:return: drbd status of resource.
:rtype: list(dict(res))
CLI Example:
.. code-block:: bash
salt '*' drbd.status
salt '*' drbd.status name=<resource name>
'''
# Initialize for multiple times test cases
global ret
global resource
ret = []
resource = {}
cmd = ['drbdadm', 'status']
cmd.append(name)
#One possible output: (number of resource/node/vol are flexible)
#resource role:Secondary
# volume:0 disk:Inconsistent
# volume:1 disk:Inconsistent
# drbd-node1 role:Primary
# volume:0 replication:SyncTarget peer-disk:UpToDate done:10.17
# volume:1 replication:SyncTarget peer-disk:UpToDate done:74.08
# drbd-node2 role:Secondary
# volume:0 peer-disk:Inconsistent resync-suspended:peer
# volume:1 peer-disk:Inconsistent resync-suspended:peer
for line in __salt__['cmd.run'](cmd).splitlines():
_line_parser(line)
if resource:
ret.append(resource)
return ret | [
"def",
"status",
"(",
"name",
"=",
"'all'",
")",
":",
"# Initialize for multiple times test cases",
"global",
"ret",
"global",
"resource",
"ret",
"=",
"[",
"]",
"resource",
"=",
"{",
"}",
"cmd",
"=",
"[",
"'drbdadm'",
",",
"'status'",
"]",
"cmd",
".",
"app... | Using drbdadm to show status of the DRBD devices,
available in the latest drbd9.
Support multiple nodes, multiple volumes.
:type name: str
:param name:
Resource name.
:return: drbd status of resource.
:rtype: list(dict(res))
CLI Example:
.. code-block:: bash
salt '*' drbd.status
salt '*' drbd.status name=<resource name> | [
"Using",
"drbdadm",
"to",
"show",
"status",
"of",
"the",
"DRBD",
"devices",
"available",
"in",
"the",
"latest",
"drbd9",
".",
"Support",
"multiple",
"nodes",
"multiple",
"volumes",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L237-L283 | train |
saltstack/salt | salt/modules/rdp.py | _parse_return_code_powershell | def _parse_return_code_powershell(string):
'''
return from the input string the return code of the powershell command
'''
regex = re.search(r'ReturnValue\s*: (\d*)', string)
if not regex:
return (False, 'Could not parse PowerShell return code.')
else:
return int(regex.group(1)) | python | def _parse_return_code_powershell(string):
'''
return from the input string the return code of the powershell command
'''
regex = re.search(r'ReturnValue\s*: (\d*)', string)
if not regex:
return (False, 'Could not parse PowerShell return code.')
else:
return int(regex.group(1)) | [
"def",
"_parse_return_code_powershell",
"(",
"string",
")",
":",
"regex",
"=",
"re",
".",
"search",
"(",
"r'ReturnValue\\s*: (\\d*)'",
",",
"string",
")",
"if",
"not",
"regex",
":",
"return",
"(",
"False",
",",
"'Could not parse PowerShell return code.'",
")",
"el... | return from the input string the return code of the powershell command | [
"return",
"from",
"the",
"input",
"string",
"the",
"return",
"code",
"of",
"the",
"powershell",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L34-L43 | train |
saltstack/salt | salt/modules/rdp.py | _psrdp | def _psrdp(cmd):
'''
Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the
command cmd returns the STDOUT of the command
'''
rdp = ('$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting '
'-Namespace root\\CIMV2\\TerminalServices -Computer . '
'-Authentication 6 -ErrorAction Stop')
return __salt__['cmd.run']('{0} ; {1}'.format(rdp, cmd),
shell='powershell', python_shell=True) | python | def _psrdp(cmd):
'''
Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the
command cmd returns the STDOUT of the command
'''
rdp = ('$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting '
'-Namespace root\\CIMV2\\TerminalServices -Computer . '
'-Authentication 6 -ErrorAction Stop')
return __salt__['cmd.run']('{0} ; {1}'.format(rdp, cmd),
shell='powershell', python_shell=True) | [
"def",
"_psrdp",
"(",
"cmd",
")",
":",
"rdp",
"=",
"(",
"'$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting '",
"'-Namespace root\\\\CIMV2\\\\TerminalServices -Computer . '",
"'-Authentication 6 -ErrorAction Stop'",
")",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
... | Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the
command cmd returns the STDOUT of the command | [
"Create",
"a",
"Win32_TerminalServiceSetting",
"WMI",
"Object",
"as",
"$RDP",
"and",
"execute",
"the",
"command",
"cmd",
"returns",
"the",
"STDOUT",
"of",
"the",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L46-L55 | train |
saltstack/salt | salt/modules/rdp.py | list_sessions | def list_sessions(logged_in_users_only=False):
'''
List information about the sessions.
.. versionadded:: 2016.11.0
:param logged_in_users_only: If True, only return sessions with users logged in.
:return: A list containing dictionaries of session information.
CLI Example:
.. code-block:: bash
salt '*' rdp.list_sessions
'''
ret = list()
server = win32ts.WTS_CURRENT_SERVER_HANDLE
protocols = {win32ts.WTS_PROTOCOL_TYPE_CONSOLE: 'console',
win32ts.WTS_PROTOCOL_TYPE_ICA: 'citrix',
win32ts.WTS_PROTOCOL_TYPE_RDP: 'rdp'}
statuses = {win32ts.WTSActive: 'active', win32ts.WTSConnected: 'connected',
win32ts.WTSConnectQuery: 'connect_query', win32ts.WTSShadow: 'shadow',
win32ts.WTSDisconnected: 'disconnected', win32ts.WTSIdle: 'idle',
win32ts.WTSListen: 'listen', win32ts.WTSReset: 'reset',
win32ts.WTSDown: 'down', win32ts.WTSInit: 'init'}
for session in win32ts.WTSEnumerateSessions(server):
user = win32ts.WTSQuerySessionInformation(server, session['SessionId'],
win32ts.WTSUserName) or None
protocol_id = win32ts.WTSQuerySessionInformation(server, session['SessionId'],
win32ts.WTSClientProtocolType)
status_id = win32ts.WTSQuerySessionInformation(server, session['SessionId'],
win32ts.WTSConnectState)
protocol = protocols.get(protocol_id, 'unknown')
connection_status = statuses.get(status_id, 'unknown')
station = session['WinStationName'] or 'Disconnected'
connection_info = {'connection_status': connection_status, 'protocol': protocol,
'session_id': session['SessionId'], 'station': station,
'user': user}
if logged_in_users_only:
if user:
ret.append(connection_info)
else:
ret.append(connection_info)
if not ret:
_LOG.warning('No sessions found.')
return sorted(ret, key=lambda k: k['session_id']) | python | def list_sessions(logged_in_users_only=False):
'''
List information about the sessions.
.. versionadded:: 2016.11.0
:param logged_in_users_only: If True, only return sessions with users logged in.
:return: A list containing dictionaries of session information.
CLI Example:
.. code-block:: bash
salt '*' rdp.list_sessions
'''
ret = list()
server = win32ts.WTS_CURRENT_SERVER_HANDLE
protocols = {win32ts.WTS_PROTOCOL_TYPE_CONSOLE: 'console',
win32ts.WTS_PROTOCOL_TYPE_ICA: 'citrix',
win32ts.WTS_PROTOCOL_TYPE_RDP: 'rdp'}
statuses = {win32ts.WTSActive: 'active', win32ts.WTSConnected: 'connected',
win32ts.WTSConnectQuery: 'connect_query', win32ts.WTSShadow: 'shadow',
win32ts.WTSDisconnected: 'disconnected', win32ts.WTSIdle: 'idle',
win32ts.WTSListen: 'listen', win32ts.WTSReset: 'reset',
win32ts.WTSDown: 'down', win32ts.WTSInit: 'init'}
for session in win32ts.WTSEnumerateSessions(server):
user = win32ts.WTSQuerySessionInformation(server, session['SessionId'],
win32ts.WTSUserName) or None
protocol_id = win32ts.WTSQuerySessionInformation(server, session['SessionId'],
win32ts.WTSClientProtocolType)
status_id = win32ts.WTSQuerySessionInformation(server, session['SessionId'],
win32ts.WTSConnectState)
protocol = protocols.get(protocol_id, 'unknown')
connection_status = statuses.get(status_id, 'unknown')
station = session['WinStationName'] or 'Disconnected'
connection_info = {'connection_status': connection_status, 'protocol': protocol,
'session_id': session['SessionId'], 'station': station,
'user': user}
if logged_in_users_only:
if user:
ret.append(connection_info)
else:
ret.append(connection_info)
if not ret:
_LOG.warning('No sessions found.')
return sorted(ret, key=lambda k: k['session_id']) | [
"def",
"list_sessions",
"(",
"logged_in_users_only",
"=",
"False",
")",
":",
"ret",
"=",
"list",
"(",
")",
"server",
"=",
"win32ts",
".",
"WTS_CURRENT_SERVER_HANDLE",
"protocols",
"=",
"{",
"win32ts",
".",
"WTS_PROTOCOL_TYPE_CONSOLE",
":",
"'console'",
",",
"win... | List information about the sessions.
.. versionadded:: 2016.11.0
:param logged_in_users_only: If True, only return sessions with users logged in.
:return: A list containing dictionaries of session information.
CLI Example:
.. code-block:: bash
salt '*' rdp.list_sessions | [
"List",
"information",
"about",
"the",
"sessions",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L104-L151 | train |
saltstack/salt | salt/modules/rdp.py | get_session | def get_session(session_id):
'''
Get information about a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A dictionary of session information.
CLI Example:
.. code-block:: bash
salt '*' rdp.get_session session_id
salt '*' rdp.get_session 99
'''
ret = dict()
sessions = list_sessions()
session = [item for item in sessions if item['session_id'] == session_id]
if session:
ret = session[0]
if not ret:
_LOG.warning('No session found for id: %s', session_id)
return ret | python | def get_session(session_id):
'''
Get information about a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A dictionary of session information.
CLI Example:
.. code-block:: bash
salt '*' rdp.get_session session_id
salt '*' rdp.get_session 99
'''
ret = dict()
sessions = list_sessions()
session = [item for item in sessions if item['session_id'] == session_id]
if session:
ret = session[0]
if not ret:
_LOG.warning('No session found for id: %s', session_id)
return ret | [
"def",
"get_session",
"(",
"session_id",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"sessions",
"=",
"list_sessions",
"(",
")",
"session",
"=",
"[",
"item",
"for",
"item",
"in",
"sessions",
"if",
"item",
"[",
"'session_id'",
"]",
"==",
"session_id",
"]",
... | Get information about a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A dictionary of session information.
CLI Example:
.. code-block:: bash
salt '*' rdp.get_session session_id
salt '*' rdp.get_session 99 | [
"Get",
"information",
"about",
"a",
"session",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L155-L181 | train |
saltstack/salt | salt/modules/rdp.py | disconnect_session | def disconnect_session(session_id):
'''
Disconnect a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A boolean representing whether the disconnect succeeded.
CLI Example:
.. code-block:: bash
salt '*' rdp.disconnect_session session_id
salt '*' rdp.disconnect_session 99
'''
try:
win32ts.WTSDisconnectSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True)
except PyWinError as error:
_LOG.error('Error calling WTSDisconnectSession: %s', error)
return False
return True | python | def disconnect_session(session_id):
'''
Disconnect a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A boolean representing whether the disconnect succeeded.
CLI Example:
.. code-block:: bash
salt '*' rdp.disconnect_session session_id
salt '*' rdp.disconnect_session 99
'''
try:
win32ts.WTSDisconnectSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True)
except PyWinError as error:
_LOG.error('Error calling WTSDisconnectSession: %s', error)
return False
return True | [
"def",
"disconnect_session",
"(",
"session_id",
")",
":",
"try",
":",
"win32ts",
".",
"WTSDisconnectSession",
"(",
"win32ts",
".",
"WTS_CURRENT_SERVER_HANDLE",
",",
"session_id",
",",
"True",
")",
"except",
"PyWinError",
"as",
"error",
":",
"_LOG",
".",
"error",... | Disconnect a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A boolean representing whether the disconnect succeeded.
CLI Example:
.. code-block:: bash
salt '*' rdp.disconnect_session session_id
salt '*' rdp.disconnect_session 99 | [
"Disconnect",
"a",
"session",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L185-L207 | train |
saltstack/salt | salt/modules/rdp.py | logoff_session | def logoff_session(session_id):
'''
Initiate the logoff of a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A boolean representing whether the logoff succeeded.
CLI Example:
.. code-block:: bash
salt '*' rdp.logoff_session session_id
salt '*' rdp.logoff_session 99
'''
try:
win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True)
except PyWinError as error:
_LOG.error('Error calling WTSLogoffSession: %s', error)
return False
return True | python | def logoff_session(session_id):
'''
Initiate the logoff of a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A boolean representing whether the logoff succeeded.
CLI Example:
.. code-block:: bash
salt '*' rdp.logoff_session session_id
salt '*' rdp.logoff_session 99
'''
try:
win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True)
except PyWinError as error:
_LOG.error('Error calling WTSLogoffSession: %s', error)
return False
return True | [
"def",
"logoff_session",
"(",
"session_id",
")",
":",
"try",
":",
"win32ts",
".",
"WTSLogoffSession",
"(",
"win32ts",
".",
"WTS_CURRENT_SERVER_HANDLE",
",",
"session_id",
",",
"True",
")",
"except",
"PyWinError",
"as",
"error",
":",
"_LOG",
".",
"error",
"(",
... | Initiate the logoff of a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A boolean representing whether the logoff succeeded.
CLI Example:
.. code-block:: bash
salt '*' rdp.logoff_session session_id
salt '*' rdp.logoff_session 99 | [
"Initiate",
"the",
"logoff",
"of",
"a",
"session",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L211-L233 | train |
saltstack/salt | salt/runners/fileserver.py | envs | def envs(backend=None, sources=False):
'''
Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.envs
salt-run fileserver.envs backend=roots,git
salt-run fileserver.envs git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
return sorted(fileserver.envs(back=backend, sources=sources)) | python | def envs(backend=None, sources=False):
'''
Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.envs
salt-run fileserver.envs backend=roots,git
salt-run fileserver.envs git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
return sorted(fileserver.envs(back=backend, sources=sources)) | [
"def",
"envs",
"(",
"backend",
"=",
"None",
",",
"sources",
"=",
"False",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"return",
"sorted",
"(",
"fileserver",
".",
"envs",
"(",
"back",
"=",
"backend",
... | Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.envs
salt-run fileserver.envs backend=roots,git
salt-run fileserver.envs git | [
"Return",
"the",
"available",
"fileserver",
"environments",
".",
"If",
"no",
"backend",
"is",
"provided",
"then",
"the",
"environments",
"for",
"all",
"configured",
"backends",
"will",
"be",
"returned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L11-L39 | train |
saltstack/salt | salt/runners/fileserver.py | clear_file_list_cache | def clear_file_list_cache(saltenv=None, backend=None):
'''
.. versionadded:: 2016.11.0
The Salt fileserver caches the files/directories/symlinks for each
fileserver backend and environment as they are requested. This is done to
help the fileserver scale better. Without this caching, when
hundreds/thousands of minions simultaneously ask the master what files are
available, this would cause the master's CPU load to spike as it obtains
the same information separately for each minion.
saltenv
By default, this runner will clear the file list caches for all
environments. This argument allows for a list of environments to be
passed, to clear more selectively. This list can be passed either as a
comma-separated string, or a Python list.
backend
Similar to the ``saltenv`` parameter, this argument will restrict the
cache clearing to specific fileserver backends (the default behavior is
to clear from all enabled fileserver backends). This list can be passed
either as a comma-separated string, or a Python list.
.. note:
The maximum age for the cached file lists (i.e. the age at which the
cache will be disregarded and rebuilt) is defined by the
:conf_master:`fileserver_list_cache_time` configuration parameter.
Since the ability to clear these caches is often required by users writing
custom runners which add/remove files, this runner can easily be called
from within a custom runner using any of the following examples:
.. code-block:: python
# Clear all file list caches
__salt__['fileserver.clear_file_list_cache']()
# Clear just the 'base' saltenv file list caches
__salt__['fileserver.clear_file_list_cache'](saltenv='base')
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
__salt__['fileserver.clear_file_list_cache'](saltenv='base', backend='roots')
# Clear all file list caches from the 'roots' fileserver backend
__salt__['fileserver.clear_file_list_cache'](backend='roots')
.. note::
In runners, the ``__salt__`` dictionary will likely be renamed to
``__runner__`` in a future Salt release to distinguish runner functions
from remote execution functions. See `this GitHub issue`_ for
discussion/updates on this.
.. _`this GitHub issue`: https://github.com/saltstack/salt/issues/34958
If using Salt's Python API (not a runner), the following examples are
equivalent to the ones above:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
opts['fun'] = 'fileserver.clear_file_list_cache'
# Clear all file list_caches
opts['arg'] = [] # No arguments
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches
opts['arg'] = ['base', None]
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
opts['arg'] = ['base', 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear all file list caches from the 'roots' fileserver backend
opts['arg'] = [None, 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
This function will return a dictionary showing a list of environments which
were cleared for each backend. An empty return dictionary means that no
changes were made.
CLI Examples:
.. code-block:: bash
# Clear all file list caches
salt-run fileserver.clear_file_list_cache
# Clear just the 'base' saltenv file list caches
salt-run fileserver.clear_file_list_cache saltenv=base
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
salt-run fileserver.clear_file_list_cache saltenv=base backend=roots
# Clear all file list caches from the 'roots' fileserver backend
salt-run fileserver.clear_file_list_cache backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.clear_file_list_cache(load=load) | python | def clear_file_list_cache(saltenv=None, backend=None):
'''
.. versionadded:: 2016.11.0
The Salt fileserver caches the files/directories/symlinks for each
fileserver backend and environment as they are requested. This is done to
help the fileserver scale better. Without this caching, when
hundreds/thousands of minions simultaneously ask the master what files are
available, this would cause the master's CPU load to spike as it obtains
the same information separately for each minion.
saltenv
By default, this runner will clear the file list caches for all
environments. This argument allows for a list of environments to be
passed, to clear more selectively. This list can be passed either as a
comma-separated string, or a Python list.
backend
Similar to the ``saltenv`` parameter, this argument will restrict the
cache clearing to specific fileserver backends (the default behavior is
to clear from all enabled fileserver backends). This list can be passed
either as a comma-separated string, or a Python list.
.. note:
The maximum age for the cached file lists (i.e. the age at which the
cache will be disregarded and rebuilt) is defined by the
:conf_master:`fileserver_list_cache_time` configuration parameter.
Since the ability to clear these caches is often required by users writing
custom runners which add/remove files, this runner can easily be called
from within a custom runner using any of the following examples:
.. code-block:: python
# Clear all file list caches
__salt__['fileserver.clear_file_list_cache']()
# Clear just the 'base' saltenv file list caches
__salt__['fileserver.clear_file_list_cache'](saltenv='base')
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
__salt__['fileserver.clear_file_list_cache'](saltenv='base', backend='roots')
# Clear all file list caches from the 'roots' fileserver backend
__salt__['fileserver.clear_file_list_cache'](backend='roots')
.. note::
In runners, the ``__salt__`` dictionary will likely be renamed to
``__runner__`` in a future Salt release to distinguish runner functions
from remote execution functions. See `this GitHub issue`_ for
discussion/updates on this.
.. _`this GitHub issue`: https://github.com/saltstack/salt/issues/34958
If using Salt's Python API (not a runner), the following examples are
equivalent to the ones above:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
opts['fun'] = 'fileserver.clear_file_list_cache'
# Clear all file list_caches
opts['arg'] = [] # No arguments
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches
opts['arg'] = ['base', None]
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
opts['arg'] = ['base', 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear all file list caches from the 'roots' fileserver backend
opts['arg'] = [None, 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
This function will return a dictionary showing a list of environments which
were cleared for each backend. An empty return dictionary means that no
changes were made.
CLI Examples:
.. code-block:: bash
# Clear all file list caches
salt-run fileserver.clear_file_list_cache
# Clear just the 'base' saltenv file list caches
salt-run fileserver.clear_file_list_cache saltenv=base
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
salt-run fileserver.clear_file_list_cache saltenv=base backend=roots
# Clear all file list caches from the 'roots' fileserver backend
salt-run fileserver.clear_file_list_cache backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.clear_file_list_cache(load=load) | [
"def",
"clear_file_list_cache",
"(",
"saltenv",
"=",
"None",
",",
"backend",
"=",
"None",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"load",
"=",
"{",
"'saltenv'",
":",
"saltenv",
",",
"'fsbackend'",
":... | .. versionadded:: 2016.11.0
The Salt fileserver caches the files/directories/symlinks for each
fileserver backend and environment as they are requested. This is done to
help the fileserver scale better. Without this caching, when
hundreds/thousands of minions simultaneously ask the master what files are
available, this would cause the master's CPU load to spike as it obtains
the same information separately for each minion.
saltenv
By default, this runner will clear the file list caches for all
environments. This argument allows for a list of environments to be
passed, to clear more selectively. This list can be passed either as a
comma-separated string, or a Python list.
backend
Similar to the ``saltenv`` parameter, this argument will restrict the
cache clearing to specific fileserver backends (the default behavior is
to clear from all enabled fileserver backends). This list can be passed
either as a comma-separated string, or a Python list.
.. note:
The maximum age for the cached file lists (i.e. the age at which the
cache will be disregarded and rebuilt) is defined by the
:conf_master:`fileserver_list_cache_time` configuration parameter.
Since the ability to clear these caches is often required by users writing
custom runners which add/remove files, this runner can easily be called
from within a custom runner using any of the following examples:
.. code-block:: python
# Clear all file list caches
__salt__['fileserver.clear_file_list_cache']()
# Clear just the 'base' saltenv file list caches
__salt__['fileserver.clear_file_list_cache'](saltenv='base')
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
__salt__['fileserver.clear_file_list_cache'](saltenv='base', backend='roots')
# Clear all file list caches from the 'roots' fileserver backend
__salt__['fileserver.clear_file_list_cache'](backend='roots')
.. note::
In runners, the ``__salt__`` dictionary will likely be renamed to
``__runner__`` in a future Salt release to distinguish runner functions
from remote execution functions. See `this GitHub issue`_ for
discussion/updates on this.
.. _`this GitHub issue`: https://github.com/saltstack/salt/issues/34958
If using Salt's Python API (not a runner), the following examples are
equivalent to the ones above:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
opts['fun'] = 'fileserver.clear_file_list_cache'
# Clear all file list_caches
opts['arg'] = [] # No arguments
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches
opts['arg'] = ['base', None]
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
opts['arg'] = ['base', 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear all file list caches from the 'roots' fileserver backend
opts['arg'] = [None, 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
This function will return a dictionary showing a list of environments which
were cleared for each backend. An empty return dictionary means that no
changes were made.
CLI Examples:
.. code-block:: bash
# Clear all file list caches
salt-run fileserver.clear_file_list_cache
# Clear just the 'base' saltenv file list caches
salt-run fileserver.clear_file_list_cache saltenv=base
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
salt-run fileserver.clear_file_list_cache saltenv=base backend=roots
# Clear all file list caches from the 'roots' fileserver backend
salt-run fileserver.clear_file_list_cache backend=roots | [
"..",
"versionadded",
"::",
"2016",
".",
"11",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L42-L147 | train |
saltstack/salt | salt/runners/fileserver.py | file_list | def file_list(saltenv='base', backend=None):
'''
Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what files are available to minions.
When in doubt, use :py:func:`cp.list_master
<salt.modules.cp.list_master>` to see what files the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Examples:
.. code-block:: bash
salt-run fileserver.file_list
salt-run fileserver.file_list saltenv=prod
salt-run fileserver.file_list saltenv=dev backend=git
salt-run fileserver.file_list base hg,roots
salt-run fileserver.file_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list(load=load) | python | def file_list(saltenv='base', backend=None):
'''
Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what files are available to minions.
When in doubt, use :py:func:`cp.list_master
<salt.modules.cp.list_master>` to see what files the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Examples:
.. code-block:: bash
salt-run fileserver.file_list
salt-run fileserver.file_list saltenv=prod
salt-run fileserver.file_list saltenv=dev backend=git
salt-run fileserver.file_list base hg,roots
salt-run fileserver.file_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list(load=load) | [
"def",
"file_list",
"(",
"saltenv",
"=",
"'base'",
",",
"backend",
"=",
"None",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"load",
"=",
"{",
"'saltenv'",
":",
"saltenv",
",",
"'fsbackend'",
":",
"back... | Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what files are available to minions.
When in doubt, use :py:func:`cp.list_master
<salt.modules.cp.list_master>` to see what files the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Examples:
.. code-block:: bash
salt-run fileserver.file_list
salt-run fileserver.file_list saltenv=prod
salt-run fileserver.file_list saltenv=dev backend=git
salt-run fileserver.file_list base hg,roots
salt-run fileserver.file_list -git | [
"Return",
"a",
"list",
"of",
"files",
"from",
"the",
"salt",
"fileserver"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L150-L193 | train |
saltstack/salt | salt/runners/fileserver.py | symlink_list | def symlink_list(saltenv='base', backend=None):
'''
Return a list of symlinked files and dirs
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what symlinks are available to minions.
When in doubt, use :py:func:`cp.list_master_symlinks
<salt.modules.cp.list_master_symlinks>` to see what symlinks the minion
can see, and always remember to restart the salt-master daemon when
updating the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.symlink_list
salt-run fileserver.symlink_list saltenv=prod
salt-run fileserver.symlink_list saltenv=dev backend=git
salt-run fileserver.symlink_list base hg,roots
salt-run fileserver.symlink_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.symlink_list(load=load) | python | def symlink_list(saltenv='base', backend=None):
'''
Return a list of symlinked files and dirs
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what symlinks are available to minions.
When in doubt, use :py:func:`cp.list_master_symlinks
<salt.modules.cp.list_master_symlinks>` to see what symlinks the minion
can see, and always remember to restart the salt-master daemon when
updating the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.symlink_list
salt-run fileserver.symlink_list saltenv=prod
salt-run fileserver.symlink_list saltenv=dev backend=git
salt-run fileserver.symlink_list base hg,roots
salt-run fileserver.symlink_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.symlink_list(load=load) | [
"def",
"symlink_list",
"(",
"saltenv",
"=",
"'base'",
",",
"backend",
"=",
"None",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"load",
"=",
"{",
"'saltenv'",
":",
"saltenv",
",",
"'fsbackend'",
":",
"b... | Return a list of symlinked files and dirs
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what symlinks are available to minions.
When in doubt, use :py:func:`cp.list_master_symlinks
<salt.modules.cp.list_master_symlinks>` to see what symlinks the minion
can see, and always remember to restart the salt-master daemon when
updating the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.symlink_list
salt-run fileserver.symlink_list saltenv=prod
salt-run fileserver.symlink_list saltenv=dev backend=git
salt-run fileserver.symlink_list base hg,roots
salt-run fileserver.symlink_list -git | [
"Return",
"a",
"list",
"of",
"symlinked",
"files",
"and",
"dirs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L196-L239 | train |
saltstack/salt | salt/runners/fileserver.py | dir_list | def dir_list(saltenv='base', backend=None):
'''
Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.dir_list(load=load) | python | def dir_list(saltenv='base', backend=None):
'''
Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.dir_list(load=load) | [
"def",
"dir_list",
"(",
"saltenv",
"=",
"'base'",
",",
"backend",
"=",
"None",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"load",
"=",
"{",
"'saltenv'",
":",
"saltenv",
",",
"'fsbackend'",
":",
"backe... | Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git | [
"Return",
"a",
"list",
"of",
"directories",
"in",
"the",
"given",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L242-L285 | train |
saltstack/salt | salt/runners/fileserver.py | empty_dir_list | def empty_dir_list(saltenv='base', backend=None):
'''
.. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list_emptydirs(load=load) | python | def empty_dir_list(saltenv='base', backend=None):
'''
.. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list_emptydirs(load=load) | [
"def",
"empty_dir_list",
"(",
"saltenv",
"=",
"'base'",
",",
"backend",
"=",
"None",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"load",
"=",
"{",
"'saltenv'",
":",
"saltenv",
",",
"'fsbackend'",
":",
... | .. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L288-L322 | train |
saltstack/salt | salt/runners/fileserver.py | update | def update(backend=None):
'''
Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
fileserver.update(back=backend)
return True | python | def update(backend=None):
'''
Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
fileserver.update(back=backend)
return True | [
"def",
"update",
"(",
"backend",
"=",
"None",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"fileserver",
".",
"update",
"(",
"back",
"=",
"backend",
")",
"return",
"True"
] | Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git | [
"Update",
"the",
"fileserver",
"cache",
".",
"If",
"no",
"backend",
"is",
"provided",
"then",
"the",
"cache",
"for",
"all",
"configured",
"backends",
"will",
"be",
"updated",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L325-L353 | train |
saltstack/salt | salt/runners/fileserver.py | clear_cache | def clear_cache(backend=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_cache(back=backend)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No cache was cleared'
return ret | python | def clear_cache(backend=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_cache(back=backend)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No cache was cleared'
return ret | [
"def",
"clear_cache",
"(",
"backend",
"=",
"None",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"cleared",
",",
"errors",
"=",
"fileserver",
".",
"clear_cache",
"(",
"back",
"=",
"backend",
")",
"ret",
... | .. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L356-L391 | train |
saltstack/salt | salt/runners/fileserver.py | clear_lock | def clear_lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_lock(back=backend, remote=remote)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were removed'
return ret | python | def clear_lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_lock(back=backend, remote=remote)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were removed'
return ret | [
"def",
"clear_lock",
"(",
"backend",
"=",
"None",
",",
"remote",
"=",
"None",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"cleared",
",",
"errors",
"=",
"fileserver",
".",
"clear_lock",
"(",
"back",
"=... | .. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L394-L432 | train |
saltstack/salt | salt/runners/fileserver.py | lock | def lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
locked, errors = fileserver.lock(back=backend, remote=remote)
ret = {}
if locked:
ret['locked'] = locked
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were set'
return ret | python | def lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
locked, errors = fileserver.lock(back=backend, remote=remote)
ret = {}
if locked:
ret['locked'] = locked
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were set'
return ret | [
"def",
"lock",
"(",
"backend",
"=",
"None",
",",
"remote",
"=",
"None",
")",
":",
"fileserver",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"__opts__",
")",
"locked",
",",
"errors",
"=",
"fileserver",
".",
"lock",
"(",
"back",
"=",
"backend... | .. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L435-L474 | train |
saltstack/salt | salt/key.py | KeyCLI.run | def run(self):
'''
Run the logic for saltkey
'''
self._update_opts()
cmd = self.opts['fun']
veri = None
ret = None
try:
if cmd in ('accept', 'reject', 'delete'):
ret = self._run_cmd('name_match')
if not isinstance(ret, dict):
salt.output.display_output(ret, 'key', opts=self.opts)
return ret
ret = self._filter_ret(cmd, ret)
if not ret:
self._print_no_match(cmd, self.opts['match'])
return
print('The following keys are going to be {0}ed:'.format(cmd.rstrip('e')))
salt.output.display_output(ret, 'key', opts=self.opts)
if not self.opts.get('yes', False):
try:
if cmd.startswith('delete'):
veri = input('Proceed? [N/y] ')
if not veri:
veri = 'n'
else:
veri = input('Proceed? [n/Y] ')
if not veri:
veri = 'y'
except KeyboardInterrupt:
raise SystemExit("\nExiting on CTRL-c")
# accept/reject/delete the same keys we're printed to the user
self.opts['match_dict'] = ret
self.opts.pop('match', None)
list_ret = ret
if veri is None or veri.lower().startswith('y'):
ret = self._run_cmd(cmd)
if cmd in ('accept', 'reject', 'delete'):
if cmd == 'delete':
ret = list_ret
for minions in ret.values():
for minion in minions:
print('Key for minion {0} {1}ed.'.format(minion,
cmd.rstrip('e')))
elif isinstance(ret, dict):
salt.output.display_output(ret, 'key', opts=self.opts)
else:
salt.output.display_output({'return': ret}, 'key', opts=self.opts)
except salt.exceptions.SaltException as exc:
ret = '{0}'.format(exc)
if not self.opts.get('quiet', False):
salt.output.display_output(ret, 'nested', self.opts)
return ret | python | def run(self):
'''
Run the logic for saltkey
'''
self._update_opts()
cmd = self.opts['fun']
veri = None
ret = None
try:
if cmd in ('accept', 'reject', 'delete'):
ret = self._run_cmd('name_match')
if not isinstance(ret, dict):
salt.output.display_output(ret, 'key', opts=self.opts)
return ret
ret = self._filter_ret(cmd, ret)
if not ret:
self._print_no_match(cmd, self.opts['match'])
return
print('The following keys are going to be {0}ed:'.format(cmd.rstrip('e')))
salt.output.display_output(ret, 'key', opts=self.opts)
if not self.opts.get('yes', False):
try:
if cmd.startswith('delete'):
veri = input('Proceed? [N/y] ')
if not veri:
veri = 'n'
else:
veri = input('Proceed? [n/Y] ')
if not veri:
veri = 'y'
except KeyboardInterrupt:
raise SystemExit("\nExiting on CTRL-c")
# accept/reject/delete the same keys we're printed to the user
self.opts['match_dict'] = ret
self.opts.pop('match', None)
list_ret = ret
if veri is None or veri.lower().startswith('y'):
ret = self._run_cmd(cmd)
if cmd in ('accept', 'reject', 'delete'):
if cmd == 'delete':
ret = list_ret
for minions in ret.values():
for minion in minions:
print('Key for minion {0} {1}ed.'.format(minion,
cmd.rstrip('e')))
elif isinstance(ret, dict):
salt.output.display_output(ret, 'key', opts=self.opts)
else:
salt.output.display_output({'return': ret}, 'key', opts=self.opts)
except salt.exceptions.SaltException as exc:
ret = '{0}'.format(exc)
if not self.opts.get('quiet', False):
salt.output.display_output(ret, 'nested', self.opts)
return ret | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_update_opts",
"(",
")",
"cmd",
"=",
"self",
".",
"opts",
"[",
"'fun'",
"]",
"veri",
"=",
"None",
"ret",
"=",
"None",
"try",
":",
"if",
"cmd",
"in",
"(",
"'accept'",
",",
"'reject'",
",",
"'delet... | Run the logic for saltkey | [
"Run",
"the",
"logic",
"for",
"saltkey"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L228-L284 | train |
saltstack/salt | salt/key.py | Key._check_minions_directories | def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied | python | def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied | [
"def",
"_check_minions_directories",
"(",
"self",
")",
":",
"minions_accepted",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"opts",
"[",
"'pki_dir'",
"]",
",",
"self",
".",
"ACC",
")",
"minions_pre",
"=",
"os",
".",
"path",
".",
"join",
"(",... | Return the minion keys directory paths | [
"Return",
"the",
"minion",
"keys",
"directory",
"paths"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L314-L325 | train |
saltstack/salt | salt/key.py | Key.gen_keys | def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub')) | python | def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub')) | [
"def",
"gen_keys",
"(",
"self",
",",
"keydir",
"=",
"None",
",",
"keyname",
"=",
"None",
",",
"keysize",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"keydir",
",",
"keyname",
",",
"keysize",
",",
"user",
"=",
"self",
".",
"_get_key_attrs",
"(",
... | Generate minion RSA public keypair | [
"Generate",
"minion",
"RSA",
"public",
"keypair"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L343-L350 | train |
saltstack/salt | salt/key.py | Key.gen_signature | def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase) | python | def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase) | [
"def",
"gen_signature",
"(",
"self",
",",
"privkey",
",",
"pubkey",
",",
"sig_path",
")",
":",
"return",
"salt",
".",
"crypt",
".",
"gen_signature",
"(",
"privkey",
",",
"pubkey",
",",
"sig_path",
",",
"self",
".",
"passphrase",
")"
] | Generate master public-key-signature | [
"Generate",
"master",
"public",
"-",
"key",
"-",
"signature"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L352-L359 | train |
saltstack/salt | salt/key.py | Key.gen_keys_signature | def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path) | python | def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path) | [
"def",
"gen_keys_signature",
"(",
"self",
",",
"priv",
",",
"pub",
",",
"signature_path",
",",
"auto_create",
"=",
"False",
",",
"keysize",
"=",
"None",
")",
":",
"# check given pub-key",
"if",
"pub",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"... | Generate master public-key-signature | [
"Generate",
"master",
"public",
"-",
"key",
"-",
"signature"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L361-L416 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.