repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/modules/systemd_service.py
_check_available
python
def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret
Returns boolean telling whether or not the named service is available
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L95-L125
[ "def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n", "def version(context=None):\n '''\n Attempts to run systemctl --version. Returns None if unable to determine\n version.\n '''\n contextkey = 'salt.utils.systemd.version'\n if isinstance(context, dict):\n # Can't put this if block on the same line as the above if block,\n # because it will break the elif below.\n if contextkey in context:\n return context[contextkey]\n elif context is not None:\n raise SaltInvocationError('context must be a dictionary if passed')\n stdout = subprocess.Popen(\n ['systemctl', '--version'],\n close_fds=True,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]\n outstr = salt.utils.stringutils.to_str(stdout)\n try:\n ret = int(re.search(r'\\w+ ([0-9]+)', outstr.splitlines()[0]).group(1))\n except (AttributeError, IndexError, ValueError):\n log.error(\n 'Unable to determine systemd version from systemctl '\n '--version, output follows:\\n%s', outstr\n )\n return None\n else:\n try:\n context[contextkey] = ret\n except TypeError:\n pass\n return ret\n", "def _systemctl_status(name):\n '''\n Helper function which leverages __context__ to keep from running 'systemctl\n status' more than once.\n '''\n contextkey = 'systemd._systemctl_status.%s' % name\n if contextkey in __context__:\n return __context__[contextkey]\n __context__[contextkey] = __salt__['cmd.run_all'](\n _systemctl_cmd('status', name),\n python_shell=False,\n redirect_stderr=True,\n ignore_retcode=True\n )\n return __context__[contextkey]\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_check_for_unit_changes
python
def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True
Check for modified/updated unit files, and run a daemon-reload if any are found.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L128-L138
[ "def _untracked_custom_unit_found(name, root=None):\n '''\n If the passed service name is not available, but a unit file exist in\n /etc/systemd/system, return True. Otherwise, return False.\n '''\n system = _root('/etc/systemd/system', root)\n unit_path = os.path.join(system, _canonical_unit_name(name))\n return os.access(unit_path, os.R_OK) and not _check_available(name)\n", "def _unit_file_changed(name):\n '''\n Returns True if systemctl reports that the unit file has changed, otherwise\n returns False.\n '''\n status = _systemctl_status(name)['stdout'].lower()\n return \"'systemctl daemon-reload'\" in status\n", "def systemctl_reload():\n '''\n .. versionadded:: 0.15.0\n\n Reloads systemctl, an action needed whenever unit files are updated.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.systemctl_reload\n '''\n out = __salt__['cmd.run_all'](\n _systemctl_cmd('--system daemon-reload'),\n python_shell=False,\n redirect_stderr=True)\n if out['retcode'] != 0:\n raise CommandExecutionError(\n 'Problem performing systemctl daemon-reload: %s' % out['stdout']\n )\n _clear_context()\n return True\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_check_unmask
python
def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root)
Common code for conditionally removing masks before making changes to a service's state.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L141-L149
[ "def unmask_(name, runtime=False, root=None):\n '''\n .. versionadded:: 2015.5.0\n .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0\n On minions running systemd>=205, `systemd-run(1)`_ is now used to\n isolate commands run by this function from the ``salt-minion`` daemon's\n control group. This is done to avoid a race condition in cases where\n the ``salt-minion`` service is restarted while a service is being\n modified. If desired, usage of `systemd-run(1)`_ can be suppressed by\n setting a :mod:`config option <salt.modules.config.get>` called\n ``systemd.scope``, with a value of ``False`` (no quotes).\n\n .. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html\n\n Unmask the specified service with systemd\n\n runtime : False\n Set to ``True`` to unmask this service only until the next reboot\n\n .. versionadded:: 2017.7.0\n In previous versions, this function would remove whichever mask was\n identified by running ``systemctl is-enabled`` on the service.\n However, since it is possible to both have both indefinite and\n runtime masks on a service simultaneously, this function now\n removes a runtime mask only when this argument is set to ``True``,\n and otherwise removes an indefinite mask.\n\n root\n Enable/disable/mask unit files in the specified root directory\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.unmask foo\n salt '*' service.unmask foo runtime=True\n '''\n _check_for_unit_changes(name)\n if not masked(name, runtime, root=root):\n log.debug('Service \\'%s\\' is not %smasked',\n name, 'runtime-' if runtime else '')\n return True\n\n cmd = 'unmask --runtime' if runtime else 'unmask'\n out = __salt__['cmd.run_all'](\n _systemctl_cmd(cmd, name, systemd_scope=True, root=root),\n python_shell=False,\n redirect_stderr=True)\n\n if out['retcode'] != 0:\n raise CommandExecutionError('Failed to unmask service \\'%s\\'' % name)\n\n return True\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_clear_context
python
def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue
Remove context
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L152-L163
null
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_default_runlevel
python
def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel
Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L166-L208
null
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_get_systemd_services
python
def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret
Use os.listdir() to get all the unit files
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L211-L229
[ "def _root(path, root):\n '''\n Relocate an absolute path to a new root directory.\n '''\n if root:\n return os.path.join(root, os.path.relpath(path, os.path.sep))\n else:\n return path\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_get_sysv_services
python
def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret
Use os.listdir() and os.access() to get all the initscripts
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L232-L269
[ "def _root(path, root):\n '''\n Relocate an absolute path to a new root directory.\n '''\n if root:\n return os.path.join(root, os.path.relpath(path, os.path.sep))\n else:\n return path\n", "def _get_systemd_services(root):\n '''\n Use os.listdir() to get all the unit files\n '''\n ret = set()\n for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,):\n # Make sure user has access to the path, and if the path is a\n # link it's likely that another entry in SYSTEM_CONFIG_PATHS\n # or LOCAL_CONFIG_PATH points to it, so we can ignore it.\n path = _root(path, root)\n if os.access(path, os.R_OK) and not os.path.islink(path):\n for fullname in os.listdir(path):\n try:\n unit_name, unit_type = fullname.rsplit('.', 1)\n except ValueError:\n continue\n if unit_type in VALID_UNIT_TYPES:\n ret.add(unit_name if unit_type == 'service' else fullname)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_get_service_exec
python
def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey]
Returns the path to the sysv service manager (either update-rc.d or chkconfig)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L272-L291
null
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_runlevel
python
def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret
Return the current runlevel
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L294-L308
[ "def _default_runlevel():\n '''\n Try to figure out the default runlevel. It is kept in\n /etc/init/rc-sysinit.conf, but can be overridden with entries\n in /etc/inittab, or via the kernel command-line at boot\n '''\n # Try to get the \"main\" default. If this fails, throw up our\n # hands and just guess \"2\", because things are horribly broken\n try:\n with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n if line.startswith('env DEFAULT_RUNLEVEL'):\n runlevel = line.split('=')[-1].strip()\n except Exception:\n return '2'\n\n # Look for an optional \"legacy\" override in /etc/inittab\n try:\n with salt.utils.files.fopen('/etc/inittab') as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n if not line.startswith('#') and 'initdefault' in line:\n runlevel = line.split(':')[1]\n except Exception:\n pass\n\n # The default runlevel can also be set via the kernel command-line.\n # Kinky.\n try:\n valid_strings = set(\n ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single'))\n with salt.utils.files.fopen('/proc/cmdline') as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n for arg in line.strip().split():\n if arg in valid_strings:\n runlevel = arg\n break\n except Exception:\n pass\n\n return runlevel\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_strip_scope
python
def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip()
Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L311-L320
null
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_systemctl_cmd
python
def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret
Build a systemctl command line. Treat unit names without one of the valid suffixes as a service.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L323-L346
[ "def has_scope(context=None):\n '''\n Scopes were introduced in systemd 205, this function returns a boolean\n which is true when the minion is systemd-booted and running systemd>=205.\n '''\n if not booted(context):\n return False\n _sd_version = version(context)\n if _sd_version is None:\n return False\n return _sd_version >= 205\n", "def _canonical_unit_name(name):\n '''\n Build a canonical unit name treating unit names without one\n of the valid suffixes as a service.\n '''\n if not isinstance(name, six.string_types):\n name = six.text_type(name)\n if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES):\n return name\n return '%s.service' % name\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_systemctl_status
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]
Helper function which leverages __context__ to keep from running 'systemctl status' more than once.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L349-L363
null
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_sysv_enabled
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
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.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L366-L377
[ "def _root(path, root):\n '''\n Relocate an absolute path to a new root directory.\n '''\n if root:\n return os.path.join(root, os.path.relpath(path, os.path.sep))\n else:\n return path\n", "def _runlevel():\n '''\n Return the current runlevel\n '''\n contextkey = 'systemd._runlevel'\n if contextkey in __context__:\n return __context__[contextkey]\n out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True)\n try:\n ret = out.split()[1]\n except IndexError:\n # The runlevel is unknown, return the default\n ret = _default_runlevel()\n __context__[contextkey] = ret\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
_untracked_custom_unit_found
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)
If the passed service name is not available, but a unit file exist in /etc/systemd/system, return True. Otherwise, return False.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L380-L387
null
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
systemctl_reload
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
.. versionadded:: 0.15.0 Reloads systemctl, an action needed whenever unit files are updated. CLI Example: .. code-block:: bash salt '*' service.systemctl_reload
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L399-L420
[ "def _clear_context():\n '''\n Remove context\n '''\n # Using list() here because modifying a dictionary during iteration will\n # raise a RuntimeError.\n for key in list(__context__):\n try:\n if key.startswith('systemd._systemctl_status.'):\n __context__.pop(key)\n except AttributeError:\n continue\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
get_running
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)
Return a list of all running services, so far as systemd is concerned CLI Example: .. code-block:: bash salt '*' service.get_running
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L423-L458
[ "def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 get_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
get_static
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)
.. 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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L547-L586
[ "def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
get_all
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)
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L589-L604
[ "def _get_systemd_services(root):\n '''\n Use os.listdir() to get all the unit files\n '''\n ret = set()\n for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,):\n # Make sure user has access to the path, and if the path is a\n # link it's likely that another entry in SYSTEM_CONFIG_PATHS\n # or LOCAL_CONFIG_PATH points to it, so we can ignore it.\n path = _root(path, root)\n if os.access(path, os.R_OK) and not os.path.islink(path):\n for fullname in os.listdir(path):\n try:\n unit_name, unit_type = fullname.rsplit('.', 1)\n except ValueError:\n continue\n if unit_type in VALID_UNIT_TYPES:\n ret.add(unit_name if unit_type == 'service' else fullname)\n return ret\n", "def _get_sysv_services(root, systemd_services=None):\n '''\n Use os.listdir() and os.access() to get all the initscripts\n '''\n initscript_path = _root(INITSCRIPT_PATH, root)\n try:\n sysv_services = os.listdir(initscript_path)\n except OSError as exc:\n if exc.errno == errno.ENOENT:\n pass\n elif exc.errno == errno.EACCES:\n log.error(\n 'Unable to check sysvinit scripts, permission denied to %s',\n initscript_path\n )\n else:\n log.error(\n 'Error %d encountered trying to check sysvinit scripts: %s',\n exc.errno,\n exc.strerror\n )\n return []\n\n if systemd_services is None:\n systemd_services = _get_systemd_services(root)\n\n ret = []\n for sysv_service in sysv_services:\n if os.access(os.path.join(initscript_path, sysv_service), os.X_OK):\n if sysv_service in systemd_services:\n log.debug(\n 'sysvinit script \\'%s\\' found, but systemd unit '\n '\\'%s.service\\' already exists',\n sysv_service, sysv_service\n )\n continue\n ret.append(sysv_service)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
unmask_
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
.. 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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L641-L693
[ "def masked(name, runtime=False, root=None):\n '''\n .. versionadded:: 2015.8.0\n .. versionchanged:: 2015.8.5\n The return data for this function has changed. If the service is\n masked, the return value will now be the output of the ``systemctl\n is-enabled`` command (so that a persistent mask can be distinguished\n from a runtime mask). If the service is not masked, then ``False`` will\n be returned.\n .. versionchanged:: 2017.7.0\n This function now returns a boolean telling the user whether a mask\n specified by the new ``runtime`` argument is set. If ``runtime`` is\n ``False``, this function will return ``True`` if an indefinite mask is\n set for the named service (otherwise ``False`` will be returned). If\n ``runtime`` is ``False``, this function will return ``True`` if a\n runtime mask is set, otherwise ``False``.\n\n Check whether or not a service is masked\n\n runtime : False\n Set to ``True`` to check for a runtime mask\n\n .. versionadded:: 2017.7.0\n In previous versions, this function would simply return the output\n of ``systemctl is-enabled`` when the service was found to be\n masked. However, since it is possible to both have both indefinite\n and runtime masks on a service simultaneously, this function now\n only checks for runtime masks if this argument is set to ``True``.\n Otherwise, it will check for an indefinite mask.\n\n root\n Enable/disable/mask unit files in the specified root directory\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' service.masked foo\n salt '*' service.masked foo runtime=True\n '''\n _check_for_unit_changes(name)\n root_dir = _root('/run' if runtime else '/etc', root)\n link_path = os.path.join(root_dir,\n 'systemd',\n 'system',\n _canonical_unit_name(name))\n try:\n return os.readlink(link_path) == '/dev/null'\n except OSError as exc:\n if exc.errno == errno.ENOENT:\n log.trace(\n 'Path %s does not exist. This is normal if service \\'%s\\' is '\n 'not masked or does not exist.', link_path, name\n )\n elif exc.errno == errno.EINVAL:\n log.error(\n 'Failed to check mask status for service %s. Path %s is a '\n 'file, not a symlink. This could be caused by changes in '\n 'systemd and is probably a bug in Salt. Please report this '\n 'to the developers.', name, link_path\n )\n return False\n", "def _check_for_unit_changes(name):\n '''\n Check for modified/updated unit files, and run a daemon-reload if any are\n found.\n '''\n contextkey = 'systemd._check_for_unit_changes.{0}'.format(name)\n if contextkey not in __context__:\n if _untracked_custom_unit_found(name) or _unit_file_changed(name):\n systemctl_reload()\n # Set context key to avoid repeating this check\n __context__[contextkey] = True\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
mask
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
.. 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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L696-L741
[ "def _check_for_unit_changes(name):\n '''\n Check for modified/updated unit files, and run a daemon-reload if any are\n found.\n '''\n contextkey = 'systemd._check_for_unit_changes.{0}'.format(name)\n if contextkey not in __context__:\n if _untracked_custom_unit_found(name) or _unit_file_changed(name):\n systemctl_reload()\n # Set context key to avoid repeating this check\n __context__[contextkey] = True\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
masked
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
.. 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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L744-L805
[ "def _root(path, root):\n '''\n Relocate an absolute path to a new root directory.\n '''\n if root:\n return os.path.join(root, os.path.relpath(path, os.path.sep))\n else:\n return path\n", "def _canonical_unit_name(name):\n '''\n Build a canonical unit name treating unit names without one\n of the valid suffixes as a service.\n '''\n if not isinstance(name, six.string_types):\n name = six.text_type(name)\n if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES):\n return name\n return '%s.service' % name\n", "def _check_for_unit_changes(name):\n '''\n Check for modified/updated unit files, and run a daemon-reload if any are\n found.\n '''\n contextkey = 'systemd._check_for_unit_changes.{0}'.format(name)\n if contextkey not in __context__:\n if _untracked_custom_unit_found(name) or _unit_file_changed(name):\n systemctl_reload()\n # Set context key to avoid repeating this check\n __context__[contextkey] = True\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
stop
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
.. 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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L864-L894
[ "def _check_for_unit_changes(name):\n '''\n Check for modified/updated unit files, and run a daemon-reload if any are\n found.\n '''\n contextkey = 'systemd._check_for_unit_changes.{0}'.format(name)\n if contextkey not in __context__:\n if _untracked_custom_unit_found(name) or _unit_file_changed(name):\n systemctl_reload()\n # Set context key to avoid repeating this check\n __context__[contextkey] = True\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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): ''' .. 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
restart
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
.. 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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L897-L950
[ "def _check_for_unit_changes(name):\n '''\n Check for modified/updated unit files, and run a daemon-reload if any are\n found.\n '''\n contextkey = 'systemd._check_for_unit_changes.{0}'.format(name)\n if contextkey not in __context__:\n if _untracked_custom_unit_found(name) or _unit_file_changed(name):\n systemctl_reload()\n # Set context key to avoid repeating this check\n __context__[contextkey] = True\n", "def _check_unmask(name, unmask, unmask_runtime, root=None):\n '''\n Common code for conditionally removing masks before making changes to a\n service's state.\n '''\n if unmask:\n unmask_(name, runtime=False, root=root)\n if unmask_runtime:\n unmask_(name, runtime=True, root=root)\n", "def _strip_scope(msg):\n '''\n Strip unnecessary message about running the command with --scope from\n stderr so that we can raise an exception with the remaining stderr text.\n '''\n ret = []\n for line in msg.splitlines():\n if not line.endswith('.scope'):\n ret.append(line)\n return '\\n'.join(ret).strip()\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
status
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]
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]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1070-L1107
[ "def get_all(root=None):\n '''\n Return a list of all available services\n\n root\n Enable/disable/mask unit files in the specified root directory\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n '''\n ret = _get_systemd_services(root)\n ret.update(set(_get_sysv_services(root, systemd_services=ret)))\n return sorted(ret)\n", "def _check_for_unit_changes(name):\n '''\n Check for modified/updated unit files, and run a daemon-reload if any are\n found.\n '''\n contextkey = 'systemd._check_for_unit_changes.{0}'.format(name)\n if contextkey not in __context__:\n if _untracked_custom_unit_found(name) or _unit_file_changed(name):\n systemctl_reload()\n # Set context key to avoid repeating this check\n __context__[contextkey] = True\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
enable
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
.. 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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1112-L1184
[ "def has_scope(context=None):\n '''\n Scopes were introduced in systemd 205, this function returns a boolean\n which is true when the minion is systemd-booted and running systemd>=205.\n '''\n if not booted(context):\n return False\n _sd_version = version(context)\n if _sd_version is None:\n return False\n return _sd_version >= 205\n", "def _check_for_unit_changes(name):\n '''\n Check for modified/updated unit files, and run a daemon-reload if any are\n found.\n '''\n contextkey = 'systemd._check_for_unit_changes.{0}'.format(name)\n if contextkey not in __context__:\n if _untracked_custom_unit_found(name) or _unit_file_changed(name):\n systemctl_reload()\n # Set context key to avoid repeating this check\n __context__[contextkey] = True\n", "def _check_unmask(name, unmask, unmask_runtime, root=None):\n '''\n Common code for conditionally removing masks before making changes to a\n service's state.\n '''\n if unmask:\n unmask_(name, runtime=False, root=root)\n if unmask_runtime:\n unmask_(name, runtime=True, root=root)\n", "def _get_sysv_services(root, systemd_services=None):\n '''\n Use os.listdir() and os.access() to get all the initscripts\n '''\n initscript_path = _root(INITSCRIPT_PATH, root)\n try:\n sysv_services = os.listdir(initscript_path)\n except OSError as exc:\n if exc.errno == errno.ENOENT:\n pass\n elif exc.errno == errno.EACCES:\n log.error(\n 'Unable to check sysvinit scripts, permission denied to %s',\n initscript_path\n )\n else:\n log.error(\n 'Error %d encountered trying to check sysvinit scripts: %s',\n exc.errno,\n exc.strerror\n )\n return []\n\n if systemd_services is None:\n systemd_services = _get_systemd_services(root)\n\n ret = []\n for sysv_service in sysv_services:\n if os.access(os.path.join(initscript_path, sysv_service), os.X_OK):\n if sysv_service in systemd_services:\n log.debug(\n 'sysvinit script \\'%s\\' found, but systemd unit '\n '\\'%s.service\\' already exists',\n sysv_service, sysv_service\n )\n continue\n ret.append(sysv_service)\n return ret\n", "def _get_service_exec():\n '''\n Returns the path to the sysv service manager (either update-rc.d or\n chkconfig)\n '''\n contextkey = 'systemd._get_service_exec'\n if contextkey not in __context__:\n executables = ('update-rc.d', 'chkconfig')\n for executable in executables:\n service_exec = salt.utils.path.which(executable)\n if service_exec is not None:\n break\n else:\n raise CommandExecutionError(\n 'Unable to find sysv service manager (tried {0})'.format(\n ', '.join(executables)\n )\n )\n __context__[contextkey] = service_exec\n return __context__[contextkey]\n", "def _strip_scope(msg):\n '''\n Strip unnecessary message about running the command with --scope from\n stderr so that we can raise an exception with the remaining stderr text.\n '''\n ret = []\n for line in msg.splitlines():\n if not line.endswith('.scope'):\n ret.append(line)\n return '\\n'.join(ret).strip()\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
disable
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
.. 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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1189-L1237
[ "def has_scope(context=None):\n '''\n Scopes were introduced in systemd 205, this function returns a boolean\n which is true when the minion is systemd-booted and running systemd>=205.\n '''\n if not booted(context):\n return False\n _sd_version = version(context)\n if _sd_version is None:\n return False\n return _sd_version >= 205\n", "def _check_for_unit_changes(name):\n '''\n Check for modified/updated unit files, and run a daemon-reload if any are\n found.\n '''\n contextkey = 'systemd._check_for_unit_changes.{0}'.format(name)\n if contextkey not in __context__:\n if _untracked_custom_unit_found(name) or _unit_file_changed(name):\n systemctl_reload()\n # Set context key to avoid repeating this check\n __context__[contextkey] = True\n", "def _get_sysv_services(root, systemd_services=None):\n '''\n Use os.listdir() and os.access() to get all the initscripts\n '''\n initscript_path = _root(INITSCRIPT_PATH, root)\n try:\n sysv_services = os.listdir(initscript_path)\n except OSError as exc:\n if exc.errno == errno.ENOENT:\n pass\n elif exc.errno == errno.EACCES:\n log.error(\n 'Unable to check sysvinit scripts, permission denied to %s',\n initscript_path\n )\n else:\n log.error(\n 'Error %d encountered trying to check sysvinit scripts: %s',\n exc.errno,\n exc.strerror\n )\n return []\n\n if systemd_services is None:\n systemd_services = _get_systemd_services(root)\n\n ret = []\n for sysv_service in sysv_services:\n if os.access(os.path.join(initscript_path, sysv_service), os.X_OK):\n if sysv_service in systemd_services:\n log.debug(\n 'sysvinit script \\'%s\\' found, but systemd unit '\n '\\'%s.service\\' already exists',\n sysv_service, sysv_service\n )\n continue\n ret.append(sysv_service)\n return ret\n", "def _get_service_exec():\n '''\n Returns the path to the sysv service manager (either update-rc.d or\n chkconfig)\n '''\n contextkey = 'systemd._get_service_exec'\n if contextkey not in __context__:\n executables = ('update-rc.d', 'chkconfig')\n for executable in executables:\n service_exec = salt.utils.path.which(executable)\n if service_exec is not None:\n break\n else:\n raise CommandExecutionError(\n 'Unable to find sysv service manager (tried {0})'.format(\n ', '.join(executables)\n )\n )\n __context__[contextkey] = service_exec\n return __context__[contextkey]\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
enabled
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
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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1242-L1276
[ "def _root(path, root):\n '''\n Relocate an absolute path to a new root directory.\n '''\n if root:\n return os.path.join(root, os.path.relpath(path, os.path.sep))\n else:\n return path\n", "def _get_sysv_services(root, systemd_services=None):\n '''\n Use os.listdir() and os.access() to get all the initscripts\n '''\n initscript_path = _root(INITSCRIPT_PATH, root)\n try:\n sysv_services = os.listdir(initscript_path)\n except OSError as exc:\n if exc.errno == errno.ENOENT:\n pass\n elif exc.errno == errno.EACCES:\n log.error(\n 'Unable to check sysvinit scripts, permission denied to %s',\n initscript_path\n )\n else:\n log.error(\n 'Error %d encountered trying to check sysvinit scripts: %s',\n exc.errno,\n exc.strerror\n )\n return []\n\n if systemd_services is None:\n systemd_services = _get_systemd_services(root)\n\n ret = []\n for sysv_service in sysv_services:\n if os.access(os.path.join(initscript_path, sysv_service), os.X_OK):\n if sysv_service in systemd_services:\n log.debug(\n 'sysvinit script \\'%s\\' found, but systemd unit '\n '\\'%s.service\\' already exists',\n sysv_service, sysv_service\n )\n continue\n ret.append(sysv_service)\n return ret\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n", "def _sysv_enabled(name, root):\n '''\n A System-V style service is assumed disabled if the \"startup\" symlink\n (starts with \"S\") to its script is found in /etc/init.d in the current\n runlevel.\n '''\n # Find exact match (disambiguate matches like \"S01anacron\" for cron)\n rc = _root('/etc/rc{}.d/S*{}'.format(_runlevel(), name), root)\n for match in glob.glob(rc):\n if re.match(r'S\\d{,2}%s' % name, os.path.basename(match)):\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. def disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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 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
saltstack/salt
salt/modules/systemd_service.py
show
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
.. 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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1295-L1326
[ "def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n", "def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,\n root=None):\n '''\n Build a systemctl command line. Treat unit names without one\n of the valid suffixes as a service.\n '''\n ret = []\n if systemd_scope \\\n and salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True):\n ret.extend(['systemd-run', '--scope'])\n ret.append('systemctl')\n if no_block:\n ret.append('--no-block')\n if root:\n ret.extend(['--root', root])\n if isinstance(action, six.string_types):\n action = shlex.split(action)\n ret.extend(action)\n if name is not None:\n ret.append(_canonical_unit_name(name))\n if 'status' in ret:\n ret.extend(['-n', '0'])\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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
saltstack/salt
salt/modules/systemd_service.py
execs
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
.. 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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L1329-L1348
[ "def show(name, root=None):\n '''\n .. versionadded:: 2014.7.0\n\n Show properties of one or more units/jobs or the manager\n\n root\n Enable/disable/mask unit files in the specified root directory\n\n CLI Example:\n\n salt '*' service.show <service name>\n '''\n ret = {}\n out = __salt__['cmd.run'](_systemctl_cmd('show', name, root=root),\n python_shell=False)\n for line in salt.utils.itertools.split(out, '\\n'):\n comps = line.split('=')\n name = comps[0]\n value = '='.join(comps[1:])\n if value.startswith('{'):\n value = value.replace('{', '').replace('}', '')\n ret[name] = {}\n for item in value.split(' ; '):\n comps = item.split('=')\n ret[name][comps[0].strip()] = comps[1].strip()\n elif name in ('Before', 'After', 'Wants'):\n ret[name] = value.split()\n else:\n ret[name] = value\n\n return ret\n", "def get_all(root=None):\n '''\n Return a list of all available services\n\n root\n Enable/disable/mask unit files in the specified root directory\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n '''\n ret = _get_systemd_services(root)\n ret.update(set(_get_sysv_services(root, systemd_services=ret)))\n return sorted(ret)\n" ]
# -*- coding: utf-8 -*- ''' Provides the service module for systemd .. versionadded:: 0.10.0 .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. .. important:: This is an implementation of virtual 'service' module. As such, you must call it under the name 'service' and NOT 'systemd'. You can see that also in the examples below. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import errno import glob import logging import os import fnmatch import re import shlex # Import Salt libs import salt.utils.files import salt.utils.itertools import salt.utils.path import salt.utils.stringutils import salt.utils.systemd from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) __func_alias__ = { 'reload_': 'reload', 'unmask_': 'unmask', } SYSTEM_CONFIG_PATHS = ('/lib/systemd/system', '/usr/lib/systemd/system') LOCAL_CONFIG_PATH = '/etc/systemd/system' INITSCRIPT_PATH = '/etc/init.d' VALID_UNIT_TYPES = ('service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer') # Define the module's virtual name __virtualname__ = 'service' # Disable check for string substitution # pylint: disable=E1321 def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' \ and salt.utils.systemd.booted(__context__): return __virtualname__ return ( False, 'The systemd execution module failed to load: only available on Linux ' 'systems which have been booted with systemd.' ) def _root(path, root): ''' Relocate an absolute path to a new root directory. ''' if root: return os.path.join(root, os.path.relpath(path, os.path.sep)) else: return path def _canonical_unit_name(name): ''' Build a canonical unit name treating unit names without one of the valid suffixes as a service. ''' if not isinstance(name, six.string_types): name = six.text_type(name) if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES): return name return '%s.service' % name def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl status" for unknown # services, and also made it return an exit status of 4. If we are on # a new enough version, check the retcode, otherwise fall back to # parsing the "systemctl status" output. # See: https://github.com/systemd/systemd/pull/3385 # Also: https://github.com/systemd/systemd/commit/3dced37 return 0 <= _status['retcode'] < 4 out = _status['stdout'].lower() if 'could not be found' in out: # Catch cases where the systemd version is < 231 but the return code # and output changes have been backported (e.g. RHEL 7.3). return False for line in salt.utils.itertools.split(out, '\n'): match = re.match(r'\s+loaded:\s+(\S+)', line) if match: ret = match.group(1) != 'not-found' break else: raise CommandExecutionError( 'Failed to get information on unit \'%s\'' % name ) return ret def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name): systemctl_reload() # Set context key to avoid repeating this check __context__[contextkey] = True def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root) def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) except AttributeError: continue def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "2", because things are horribly broken try: with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('env DEFAULT_RUNLEVEL'): runlevel = line.split('=')[-1].strip() except Exception: return '2' # Look for an optional "legacy" override in /etc/inittab try: with salt.utils.files.fopen('/etc/inittab') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if not line.startswith('#') and 'initdefault' in line: runlevel = line.split(':')[1] except Exception: pass # The default runlevel can also be set via the kernel command-line. # Kinky. try: valid_strings = set( ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single')) with salt.utils.files.fopen('/proc/cmdline') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) for arg in line.strip().split(): if arg in valid_strings: runlevel = arg break except Exception: pass return runlevel def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS # or LOCAL_CONFIG_PATH points to it, so we can ignore it. path = _root(path, root) if os.access(path, os.R_OK) and not os.path.islink(path): for fullname in os.listdir(path): 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 ret def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: pass elif exc.errno == errno.EACCES: log.error( 'Unable to check sysvinit scripts, permission denied to %s', initscript_path ) else: log.error( 'Error %d encountered trying to check sysvinit scripts: %s', exc.errno, exc.strerror ) return [] if systemd_services is None: systemd_services = _get_systemd_services(root) ret = [] for sysv_service in sysv_services: if os.access(os.path.join(initscript_path, sysv_service), os.X_OK): if sysv_service in systemd_services: log.debug( 'sysvinit script \'%s\' found, but systemd unit ' '\'%s.service\' already exists', sysv_service, sysv_service ) continue ret.append(sysv_service) return ret def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service_exec = salt.utils.path.which(executable) if service_exec is not None: break else: raise CommandExecutionError( 'Unable to find sysv service manager (tried {0})'.format( ', '.join(executables) ) ) __context__[contextkey] = service_exec return __context__[contextkey] def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: # The runlevel is unknown, return the default ret = _default_runlevel() __context__[contextkey] = ret return ret def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n'.join(ret).strip() def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): ret.extend(['systemd-run', '--scope']) ret.append('systemctl') if no_block: ret.append('--no-block') if root: ret.extend(['--root', root]) if isinstance(action, six.string_types): action = shlex.split(action) ret.extend(action) if name is not None: ret.append(_canonical_unit_name(name)) if 'status' in ret: ret.extend(['-n', '0']) return ret 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 _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 _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 _unit_file_changed(name): ''' Returns True if systemctl reports that the unit file has changed, otherwise returns False. ''' status = _systemctl_status(name)['stdout'].lower() return "'systemctl daemon-reload'" in status 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 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_enabled(root=None): ''' Return a list of all enabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' ret = set() # Get enabled systemd units. Can't use --state=enabled 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 != 'enabled': 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) # Add in any sysvinit services that are enabled ret.update(set( [x for x in _get_sysv_services(root) if _sysv_enabled(x, root)] )) return sorted(ret) def get_disabled(root=None): ''' Return a list of all disabled services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' ret = set() # Get disabled systemd units. Can't use --state=disabled 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 != 'disabled': 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) # Add in any sysvinit services that are disabled ret.update(set( [x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)] )) return sorted(ret) 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_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 available(name): ''' .. versionadded:: 0.10.4 Check that the given service is available taking into account template units. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' _check_for_unit_changes(name) return _check_available(name) def missing(name): ''' .. versionadded:: 2014.1.0 The inverse of :py:func:`service.available <salt.modules.systemd.available>`. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) 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 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 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 start(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 Start 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 start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to start the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before starting. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('start', 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 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 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 reload_(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 Reload the specified service with systemd no_block : False Set to ``True`` to reload the service using ``--no-block``. .. versionadded:: 2017.7.0 unmask : False Set to ``True`` to remove an indefinite mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('reload', 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 force_reload(name, no_block=True, 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 .. versionadded:: 0.12.0 Force-reload 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 force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. unmask_runtime : False Set to ``True`` to remove a runtime mask before attempting to force-reload the service. .. versionadded:: 2017.7.0 In previous releases, Salt would simply unmask a service before force-reloading. This behavior is no longer the default. CLI Example: .. code-block:: bash salt '*' service.force_reload <service name> ''' _check_for_unit_changes(name) _check_unmask(name, unmask, unmask_runtime) ret = __salt__['cmd.run_all']( _systemctl_cmd('force-reload', 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 # The unused sig argument is required to maintain consistency with the API # established by Salt's service management states. 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] # **kwargs is required to maintain consistency with the API established by # Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 # The unused kwargs argument is required to maintain consistency with the API # established by Salt's service management states. 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 disabled(name, root=None): ''' Return if the named service is disabled from starting on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name, root=root) 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
saltstack/salt
salt/states/virt.py
keys
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L51-L145
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n" ]
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 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 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 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 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) # Deprecated states 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 unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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 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
saltstack/salt
salt/states/virt.py
_virt_call
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
Helper to call the virt functions. Wildcards supported. :param domain: :param function: :param section: :param comment: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L148-L184
null
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 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 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 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 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) # Deprecated states 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 unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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 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
saltstack/salt
salt/states/virt.py
stopped
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)
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L187-L210
[ "def _virt_call(domain, function, section, comment,\n connection=None, username=None, password=None, **kwargs):\n '''\n Helper to call the virt functions. Wildcards supported.\n\n :param domain:\n :param function:\n :param section:\n :param comment:\n :return:\n '''\n ret = {'name': domain, 'changes': {}, 'result': True, 'comment': ''}\n targeted_domains = fnmatch.filter(__salt__['virt.list_domains'](), domain)\n changed_domains = list()\n ignored_domains = list()\n for targeted_domain in targeted_domains:\n try:\n response = __salt__['virt.{0}'.format(function)](targeted_domain,\n connection=connection,\n username=username,\n password=password,\n **kwargs)\n if isinstance(response, dict):\n response = response['name']\n changed_domains.append({'domain': targeted_domain, function: response})\n except libvirt.libvirtError as err:\n ignored_domains.append({'domain': targeted_domain, 'issue': six.text_type(err)})\n if not changed_domains:\n ret['result'] = False\n ret['comment'] = 'No changes had happened'\n if ignored_domains:\n ret['changes'] = {'ignored': ignored_domains}\n else:\n ret['changes'] = {section: changed_domains}\n ret['comment'] = comment\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 _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 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 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 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) # Deprecated states 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 unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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 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
saltstack/salt
salt/states/virt.py
powered_off
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)
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L213-L236
[ "def _virt_call(domain, function, section, comment,\n connection=None, username=None, password=None, **kwargs):\n '''\n Helper to call the virt functions. Wildcards supported.\n\n :param domain:\n :param function:\n :param section:\n :param comment:\n :return:\n '''\n ret = {'name': domain, 'changes': {}, 'result': True, 'comment': ''}\n targeted_domains = fnmatch.filter(__salt__['virt.list_domains'](), domain)\n changed_domains = list()\n ignored_domains = list()\n for targeted_domain in targeted_domains:\n try:\n response = __salt__['virt.{0}'.format(function)](targeted_domain,\n connection=connection,\n username=username,\n password=password,\n **kwargs)\n if isinstance(response, dict):\n response = response['name']\n changed_domains.append({'domain': targeted_domain, function: response})\n except libvirt.libvirtError as err:\n ignored_domains.append({'domain': targeted_domain, 'issue': six.text_type(err)})\n if not changed_domains:\n ret['result'] = False\n ret['comment'] = 'No changes had happened'\n if ignored_domains:\n ret['changes'] = {'ignored': ignored_domains}\n else:\n ret['changes'] = {section: changed_domains}\n ret['comment'] = comment\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 _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 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 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 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) # Deprecated states 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 unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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 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
saltstack/salt
salt/states/virt.py
running
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L239-L481
[ "def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n" ]
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 _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 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 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 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) # Deprecated states 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 unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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 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
saltstack/salt
salt/states/virt.py
snapshot
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)
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L484-L512
[ "def _virt_call(domain, function, section, comment,\n connection=None, username=None, password=None, **kwargs):\n '''\n Helper to call the virt functions. Wildcards supported.\n\n :param domain:\n :param function:\n :param section:\n :param comment:\n :return:\n '''\n ret = {'name': domain, 'changes': {}, 'result': True, 'comment': ''}\n targeted_domains = fnmatch.filter(__salt__['virt.list_domains'](), domain)\n changed_domains = list()\n ignored_domains = list()\n for targeted_domain in targeted_domains:\n try:\n response = __salt__['virt.{0}'.format(function)](targeted_domain,\n connection=connection,\n username=username,\n password=password,\n **kwargs)\n if isinstance(response, dict):\n response = response['name']\n changed_domains.append({'domain': targeted_domain, function: response})\n except libvirt.libvirtError as err:\n ignored_domains.append({'domain': targeted_domain, 'issue': six.text_type(err)})\n if not changed_domains:\n ret['result'] = False\n ret['comment'] = 'No changes had happened'\n if ignored_domains:\n ret['changes'] = {'ignored': ignored_domains}\n else:\n ret['changes'] = {section: changed_domains}\n ret['comment'] = comment\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 _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 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 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 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 # Deprecated states 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 unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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 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
saltstack/salt
salt/states/virt.py
rebooted
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)
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L516-L536
[ "def _virt_call(domain, function, section, comment,\n connection=None, username=None, password=None, **kwargs):\n '''\n Helper to call the virt functions. Wildcards supported.\n\n :param domain:\n :param function:\n :param section:\n :param comment:\n :return:\n '''\n ret = {'name': domain, 'changes': {}, 'result': True, 'comment': ''}\n targeted_domains = fnmatch.filter(__salt__['virt.list_domains'](), domain)\n changed_domains = list()\n ignored_domains = list()\n for targeted_domain in targeted_domains:\n try:\n response = __salt__['virt.{0}'.format(function)](targeted_domain,\n connection=connection,\n username=username,\n password=password,\n **kwargs)\n if isinstance(response, dict):\n response = response['name']\n changed_domains.append({'domain': targeted_domain, function: response})\n except libvirt.libvirtError as err:\n ignored_domains.append({'domain': targeted_domain, 'issue': six.text_type(err)})\n if not changed_domains:\n ret['result'] = False\n ret['comment'] = 'No changes had happened'\n if ignored_domains:\n ret['changes'] = {'ignored': ignored_domains}\n else:\n ret['changes'] = {section: changed_domains}\n ret['comment'] = comment\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 _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 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 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 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 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) # Deprecated states def unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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 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
saltstack/salt
salt/states/virt.py
reverted
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
.. 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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L580-L636
null
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 _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 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 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 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 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) # Deprecated states 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 unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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
saltstack/salt
salt/states/virt.py
network_running
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L639-L709
null
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 _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 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 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 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 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) # Deprecated states 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 unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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
saltstack/salt
salt/states/virt.py
pool_running
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L712-L826
null
# -*- coding: utf-8 -*- ''' Manage virt =========== For the key certificate this state uses the external pillar in the master to call for the generation and signing of certificates for systems running libvirt: .. code-block:: yaml libvirt_keys: virt.keys ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import fnmatch import os try: import libvirt # pylint: disable=import-error HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import Salt libs import salt.utils.args import salt.utils.files import salt.utils.stringutils import salt.utils.versions from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six __virtualname__ = 'virt' def __virtual__(): ''' Only if virt module is available. :return: ''' if 'virt.node_info' in __salt__: return __virtualname__ return False 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 _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 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 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 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 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) # Deprecated states 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 unpowered(name): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.powered_off` instead. Stops a VM by power off. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.stopped ''' return _virt_call(name, 'stop', 'unpowered', 'Machine has been powered off') def saved(name, suffix=None): ''' .. deprecated:: 2016.3.0 Use :py:func:`~salt.modules.virt.snapshot` instead. Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.saved: - suffix: periodic domain*: virt.saved: - suffix: periodic ''' return _virt_call(name, 'snapshot', 'saved', 'Snapshots has been taken', suffix=suffix) 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 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
saltstack/salt
salt/modules/runit.py
status
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
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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L206-L240
[ "def _service_path(name):\n '''\n Return SERVICE_DIR+name if possible\n\n name\n the service's name to work on\n '''\n if not SERVICE_DIR:\n raise CommandExecutionError('Could not find service directory.')\n return os.path.join(SERVICE_DIR, name)\n" ]
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
_is_svc
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L243-L256
null
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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_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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
status_autostart
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'))
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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L259-L274
[ "def _service_path(name):\n '''\n Return SERVICE_DIR+name if possible\n\n name\n the service's name to work on\n '''\n if not SERVICE_DIR:\n raise CommandExecutionError('Could not find service directory.')\n return os.path.join(SERVICE_DIR, name)\n" ]
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
get_svc_broken_path
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)
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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L277-L300
null
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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 get_svc_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
add_svc_avail_path
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L310-L322
null
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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_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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
_get_svc_path
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)
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)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L325-L374
null
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
_get_svc_list
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)])
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)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L377-L389
[ "def _get_svc_path(name='*', status=None):\n '''\n Return a list of paths to services with ``name`` that have the specified ``status``\n\n name\n a glob for service name. default is '*'\n\n status\n None : all services (no filter, default choice)\n 'DISABLED' : available service(s) that is not enabled\n 'ENABLED' : enabled service (whether started on boot or not)\n '''\n\n # This is the core routine to work with services, called by many\n # other functions of this module.\n #\n # The name of a service is the \"apparent\" folder's name that contains its\n # \"run\" script. If its \"folder\" is a symlink, the service is an \"alias\" of\n # the targeted service.\n\n if not SERVICE_DIR:\n raise CommandExecutionError('Could not find service directory.')\n\n # path list of enabled services as /AVAIL_SVR_DIRS/$service,\n # taking care of any service aliases (do not use os.path.realpath()).\n ena = set()\n for el in glob.glob(os.path.join(SERVICE_DIR, name)):\n if _is_svc(el):\n ena.add(os.readlink(el))\n log.trace('found enabled service path: %s', el)\n\n if status == 'ENABLED':\n return sorted(ena)\n\n # path list of available services as /AVAIL_SVR_DIRS/$service\n ava = set()\n for d in AVAIL_SVR_DIRS:\n for el in glob.glob(os.path.join(d, name)):\n if _is_svc(el):\n ava.add(el)\n log.trace('found available service path: %s', el)\n\n if status == 'DISABLED':\n # service available but not enabled\n ret = ava.difference(ena)\n else:\n # default: return available services\n ret = ava.union(ena)\n\n return sorted(ret)\n" ]
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
get_svc_alias
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
Returns the list of service's name that are aliased and their alias path(s)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L392-L409
null
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
show
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
Show properties of one or more units/jobs or the manager name the service's name CLI Example: salt '*' service.show <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L520-L553
[ "def status(name, sig=None):\n '''\n Return ``True`` if service is running\n\n name\n the service's name\n\n sig\n signature to identify with ps\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' runit.status <service name>\n '''\n if sig:\n # usual way to do by others (debian_service, netbsdservice).\n # XXX probably does not work here (check 'runsv sshd' instead of 'sshd' ?)\n return bool(__salt__['status.pid'](sig))\n\n svc_path = _service_path(name)\n if not os.path.exists(svc_path):\n # service does not exist\n return False\n\n # sv return code is not relevant to get a service status.\n # Check its output instead.\n cmd = 'sv status {0}'.format(svc_path)\n try:\n out = __salt__['cmd.run_stdout'](cmd)\n return out.startswith('run: ')\n except Exception:\n # sv (as a command) returned an error\n return False\n", "def available(name):\n '''\n Returns ``True`` if the specified service is available, otherwise returns\n ``False``.\n\n name\n the service's name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' runit.available <service name>\n '''\n return name in _get_svc_list(name)\n", "def enabled(name):\n '''\n Return ``True`` if the named service is enabled, ``False`` otherwise\n\n name\n the service's name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.enabled <service name>\n '''\n # exhaustive check instead of (only) os.path.exists(_service_path(name))\n return name in _get_svc_list(name, 'ENABLED')\n", "def status_autostart(name):\n '''\n Return ``True`` if service <name> is autostarted by sv\n (file $service_folder/down does not exist)\n NB: return ``False`` if the service is not enabled.\n\n name\n the service's name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' runit.status_autostart <service name>\n '''\n return not os.path.exists(os.path.join(_service_path(name), 'down'))\n", "def _get_svc_path(name='*', status=None):\n '''\n Return a list of paths to services with ``name`` that have the specified ``status``\n\n name\n a glob for service name. default is '*'\n\n status\n None : all services (no filter, default choice)\n 'DISABLED' : available service(s) that is not enabled\n 'ENABLED' : enabled service (whether started on boot or not)\n '''\n\n # This is the core routine to work with services, called by many\n # other functions of this module.\n #\n # The name of a service is the \"apparent\" folder's name that contains its\n # \"run\" script. If its \"folder\" is a symlink, the service is an \"alias\" of\n # the targeted service.\n\n if not SERVICE_DIR:\n raise CommandExecutionError('Could not find service directory.')\n\n # path list of enabled services as /AVAIL_SVR_DIRS/$service,\n # taking care of any service aliases (do not use os.path.realpath()).\n ena = set()\n for el in glob.glob(os.path.join(SERVICE_DIR, name)):\n if _is_svc(el):\n ena.add(os.readlink(el))\n log.trace('found enabled service path: %s', el)\n\n if status == 'ENABLED':\n return sorted(ena)\n\n # path list of available services as /AVAIL_SVR_DIRS/$service\n ava = set()\n for d in AVAIL_SVR_DIRS:\n for el in glob.glob(os.path.join(d, name)):\n if _is_svc(el):\n ava.add(el)\n log.trace('found available service path: %s', el)\n\n if status == 'DISABLED':\n # service available but not enabled\n ret = ava.difference(ena)\n else:\n # default: return available services\n ret = ava.union(ena)\n\n return sorted(ret)\n" ]
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
enable
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
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]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L556-L648
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def available(name):\n '''\n Returns ``True`` if the specified service is available, otherwise returns\n ``False``.\n\n name\n the service's name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' runit.available <service name>\n '''\n return name in _get_svc_list(name)\n", "def enabled(name):\n '''\n Return ``True`` if the named service is enabled, ``False`` otherwise\n\n name\n the service's name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.enabled <service name>\n '''\n # exhaustive check instead of (only) os.path.exists(_service_path(name))\n return name in _get_svc_list(name, 'ENABLED')\n", "def _service_path(name):\n '''\n Return SERVICE_DIR+name if possible\n\n name\n the service's name to work on\n '''\n if not SERVICE_DIR:\n raise CommandExecutionError('Could not find service directory.')\n return os.path.join(SERVICE_DIR, name)\n", "def _get_svc_path(name='*', status=None):\n '''\n Return a list of paths to services with ``name`` that have the specified ``status``\n\n name\n a glob for service name. default is '*'\n\n status\n None : all services (no filter, default choice)\n 'DISABLED' : available service(s) that is not enabled\n 'ENABLED' : enabled service (whether started on boot or not)\n '''\n\n # This is the core routine to work with services, called by many\n # other functions of this module.\n #\n # The name of a service is the \"apparent\" folder's name that contains its\n # \"run\" script. If its \"folder\" is a symlink, the service is an \"alias\" of\n # the targeted service.\n\n if not SERVICE_DIR:\n raise CommandExecutionError('Could not find service directory.')\n\n # path list of enabled services as /AVAIL_SVR_DIRS/$service,\n # taking care of any service aliases (do not use os.path.realpath()).\n ena = set()\n for el in glob.glob(os.path.join(SERVICE_DIR, name)):\n if _is_svc(el):\n ena.add(os.readlink(el))\n log.trace('found enabled service path: %s', el)\n\n if status == 'ENABLED':\n return sorted(ena)\n\n # path list of available services as /AVAIL_SVR_DIRS/$service\n ava = set()\n for d in AVAIL_SVR_DIRS:\n for el in glob.glob(os.path.join(d, name)):\n if _is_svc(el):\n ava.add(el)\n log.trace('found available service path: %s', el)\n\n if status == 'DISABLED':\n # service available but not enabled\n ret = ava.difference(ena)\n else:\n # default: return available services\n ret = ava.union(ena)\n\n return sorted(ret)\n", "def get_svc_alias():\n '''\n Returns the list of service's name that are aliased and their alias path(s)\n '''\n\n ret = {}\n for d in AVAIL_SVR_DIRS:\n for el in glob.glob(os.path.join(d, '*')):\n if not os.path.islink(el):\n continue\n psvc = os.readlink(el)\n if not os.path.isabs(psvc):\n psvc = os.path.join(d, psvc)\n nsvc = os.path.basename(psvc)\n if nsvc not in ret:\n ret[nsvc] = []\n ret[nsvc].append(el)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
disable
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
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]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L651-L687
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def enabled(name):\n '''\n Return ``True`` if the named service is enabled, ``False`` otherwise\n\n name\n the service's name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.enabled <service name>\n '''\n # exhaustive check instead of (only) os.path.exists(_service_path(name))\n return name in _get_svc_list(name, 'ENABLED')\n", "def _get_svc_path(name='*', status=None):\n '''\n Return a list of paths to services with ``name`` that have the specified ``status``\n\n name\n a glob for service name. default is '*'\n\n status\n None : all services (no filter, default choice)\n 'DISABLED' : available service(s) that is not enabled\n 'ENABLED' : enabled service (whether started on boot or not)\n '''\n\n # This is the core routine to work with services, called by many\n # other functions of this module.\n #\n # The name of a service is the \"apparent\" folder's name that contains its\n # \"run\" script. If its \"folder\" is a symlink, the service is an \"alias\" of\n # the targeted service.\n\n if not SERVICE_DIR:\n raise CommandExecutionError('Could not find service directory.')\n\n # path list of enabled services as /AVAIL_SVR_DIRS/$service,\n # taking care of any service aliases (do not use os.path.realpath()).\n ena = set()\n for el in glob.glob(os.path.join(SERVICE_DIR, name)):\n if _is_svc(el):\n ena.add(os.readlink(el))\n log.trace('found enabled service path: %s', el)\n\n if status == 'ENABLED':\n return sorted(ena)\n\n # path list of available services as /AVAIL_SVR_DIRS/$service\n ava = set()\n for d in AVAIL_SVR_DIRS:\n for el in glob.glob(os.path.join(d, name)):\n if _is_svc(el):\n ava.add(el)\n log.trace('found available service path: %s', el)\n\n if status == 'DISABLED':\n # service available but not enabled\n ret = ava.difference(ena)\n else:\n # default: return available services\n ret = ava.union(ena)\n\n return sorted(ret)\n" ]
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/modules/runit.py
remove
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
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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L690-L722
[ "def stop(name):\n '''\n Stop service\n\n name\n the service's name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' runit.stop <service name>\n '''\n cmd = 'sv stop {0}'.format(_service_path(name))\n return not __salt__['cmd.retcode'](cmd)\n", "def enabled(name):\n '''\n Return ``True`` if the named service is enabled, ``False`` otherwise\n\n name\n the service's name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.enabled <service name>\n '''\n # exhaustive check instead of (only) os.path.exists(_service_path(name))\n return name in _get_svc_list(name, 'ENABLED')\n", "def _service_path(name):\n '''\n Return SERVICE_DIR+name if possible\n\n name\n the service's name to work on\n '''\n if not SERVICE_DIR:\n raise CommandExecutionError('Could not find service directory.')\n return os.path.join(SERVICE_DIR, name)\n" ]
# -*- coding: utf-8 -*- ''' runit service module (http://smarden.org/runit) This module is compatible with the :mod:`service <salt.states.service>` states, so it can be used to maintain services using the ``provider`` argument: .. code-block:: yaml myservice: service: - running - provider: runit Provides virtual `service` module on systems using runit as init. Service management rules (`sv` command): service $n is ENABLED if file SERVICE_DIR/$n/run exists service $n is AVAILABLE if ENABLED or if file AVAIL_SVR_DIR/$n/run exists service $n is DISABLED if AVAILABLE but not ENABLED SERVICE_DIR/$n is normally a symlink to a AVAIL_SVR_DIR/$n folder Service auto-start/stop mechanism: `sv` (auto)starts/stops service as soon as SERVICE_DIR/<service> is created/deleted, both on service creation or a boot time. autostart feature is disabled if file SERVICE_DIR/<n>/down exists. This does not affect the current's service status (if already running) nor manual service management. Service's alias: Service `sva` is an alias of service `svc` when `AVAIL_SVR_DIR/sva` symlinks to folder `AVAIL_SVR_DIR/svc`. `svc` can't be enabled if it is already enabled through an alias already enabled, since `sv` files are stored in folder `SERVICE_DIR/svc/`. XBPS package management uses a service's alias to provides service alternative(s), such as chrony and openntpd both aliased to ntpd. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import glob import logging import time log = logging.getLogger(__name__) # Import salt libs from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.path # Function alias to not shadow built-ins. __func_alias__ = { 'reload_': 'reload' } # which dir sv works with VALID_SERVICE_DIRS = [ '/service', '/var/service', '/etc/service', ] SERVICE_DIR = None for service_dir in VALID_SERVICE_DIRS: if os.path.exists(service_dir): SERVICE_DIR = service_dir break # available service directory(ies) AVAIL_SVR_DIRS = [] # Define the module's virtual name __virtualname__ = 'runit' __virtual_aliases__ = ('runit',) def __virtual__(): ''' Virtual service only on systems using runit as init process (PID 1). Otherwise, use this module with the provider mechanism. ''' if __grains__.get('init') == 'runit': if __grains__['os'] == 'Void': add_svc_avail_path('/etc/sv') global __virtualname__ __virtualname__ = 'service' return __virtualname__ if salt.utils.path.which('sv'): return __virtualname__ return (False, 'Runit not available. Please install sv') def _service_path(name): ''' Return SERVICE_DIR+name if possible name the service's name to work on ''' if not SERVICE_DIR: raise CommandExecutionError('Could not find service directory.') return os.path.join(SERVICE_DIR, name) #-- states.service compatible args def start(name): ''' Start service name the service's name CLI Example: .. code-block:: bash salt '*' runit.start <service name> ''' cmd = 'sv start {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible args def stop(name): ''' Stop service name the service's name CLI Example: .. code-block:: bash salt '*' runit.stop <service name> ''' cmd = 'sv stop {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def reload_(name): ''' Reload service name the service's name CLI Example: .. code-block:: bash salt '*' runit.reload <service name> ''' cmd = 'sv reload {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def restart(name): ''' Restart service name the service's name CLI Example: .. code-block:: bash salt '*' runit.restart <service name> ''' cmd = 'sv restart {0}'.format(_service_path(name)) return not __salt__['cmd.retcode'](cmd) #-- states.service compatible def full_restart(name): ''' Calls runit.restart() name the service's name CLI Example: .. code-block:: bash salt '*' runit.full_restart <service name> ''' restart(name) #-- states.service compatible 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 _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 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 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_avail_path(): ''' Return list of paths that may contain available services ''' return AVAIL_SVR_DIRS 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 _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_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_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 available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.available <service name> ''' return name in _get_svc_list(name) def missing(name): ''' The inverse of runit.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. name the service's name CLI Example: .. code-block:: bash salt '*' runit.missing <service name> ''' return name not in _get_svc_list(name) def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' runit.get_all ''' return _get_svc_list() def get_enabled(): ''' Return a list of all enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' return _get_svc_list(status='ENABLED') def get_disabled(): ''' Return a list of all disabled services CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' return _get_svc_list(status='DISABLED') def enabled(name): ''' Return ``True`` if the named service is enabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' # exhaustive check instead of (only) os.path.exists(_service_path(name)) return name in _get_svc_list(name, 'ENABLED') def disabled(name): ''' Return ``True`` if the named service is disabled, ``False`` otherwise name the service's name CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' # return True for a non-existent service return name not in _get_svc_list(name, 'ENABLED') 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 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 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 # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
saltstack/salt
salt/pillar/s3.py
ext_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
Execute a command and read the output as YAML
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L129-L189
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _init(creds, bucket, multiple_env, environment, prefix, s3_cache_expire):\n '''\n Connect to S3 and download the metadata for each file in all buckets\n specified and cache the data to disk.\n '''\n\n cache_file = _get_buckets_cache_filename(bucket, prefix)\n exp = time.time() - s3_cache_expire\n\n # check if cache_file exists and its mtime\n if os.path.isfile(cache_file):\n cache_file_mtime = os.path.getmtime(cache_file)\n else:\n # file does not exists then set mtime to 0 (aka epoch)\n cache_file_mtime = 0\n\n expired = (cache_file_mtime <= exp)\n\n log.debug(\n 'S3 bucket cache file %s is %sexpired, mtime_diff=%ss, expiration=%ss',\n cache_file,\n '' if expired else 'not ',\n cache_file_mtime - exp,\n s3_cache_expire\n )\n\n if expired:\n pillars = _refresh_buckets_cache_file(creds, cache_file, multiple_env,\n environment, prefix)\n else:\n pillars = _read_buckets_cache_file(cache_file)\n\n log.debug('S3 bucket retrieved pillars %s', pillars)\n return pillars\n", "def _get_cache_dir():\n '''\n Get pillar cache directory. Initialize it if it does not exist.\n '''\n\n cache_dir = os.path.join(__opts__['cachedir'], 'pillar_s3fs')\n\n if not os.path.isdir(cache_dir):\n log.debug('Initializing S3 Pillar Cache')\n os.makedirs(cache_dir)\n\n return cache_dir\n", "def _find_files(metadata):\n '''\n Looks for all the files in the S3 bucket cache metadata\n '''\n\n ret = {}\n\n for bucket, data in six.iteritems(metadata):\n if bucket not in ret:\n ret[bucket] = []\n\n # grab the paths from the metadata\n filePaths = [k['Key'] for k in data]\n # filter out the dirs\n ret[bucket] += [k for k in filePaths if not k.endswith('/')]\n\n return ret\n", "def _get_cached_file_name(bucket, saltenv, path):\n '''\n Return the cached file name for a bucket path file\n '''\n\n file_path = os.path.join(_get_cache_dir(), saltenv, bucket, path)\n\n # make sure bucket and saltenv directories exist\n if not os.path.exists(os.path.dirname(file_path)):\n os.makedirs(os.path.dirname(file_path))\n\n return file_path\n", "def _get_file_from_s3(creds, metadata, saltenv, bucket, path,\n cached_file_path):\n '''\n Checks the local cache for the file, if it's old or missing go grab the\n file from S3 and update the cache\n '''\n\n # check the local cache...\n if os.path.isfile(cached_file_path):\n file_meta = _find_file_meta(metadata, bucket, saltenv, path)\n file_md5 = \"\".join(list(filter(str.isalnum, file_meta['ETag']))) \\\n if file_meta else None\n\n cached_md5 = salt.utils.hashutils.get_hash(cached_file_path, 'md5')\n\n # hashes match we have a cache hit\n log.debug('Cached file: path=%s, md5=%s, etag=%s',\n cached_file_path, cached_md5, file_md5)\n if cached_md5 == file_md5:\n return\n\n # ... or get the file from S3\n __utils__['s3.query'](\n key=creds.key,\n keyid=creds.keyid,\n kms_keyid=creds.kms_keyid,\n bucket=bucket,\n service_url=creds.service_url,\n path=_quote(path),\n local_file=cached_file_path,\n verify_ssl=creds.verify_ssl,\n location=creds.location,\n path_style=creds.path_style,\n https_enable=creds.https_enable\n )\n", "def compile_pillar(self, ext=True):\n '''\n Render the pillar data and return\n '''\n top, top_errors = self.get_top()\n if ext:\n if self.opts.get('ext_pillar_first', False):\n self.opts['pillar'], errors = self.ext_pillar(self.pillar_override)\n self.rend = salt.loader.render(self.opts, self.functions)\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches, errors=errors)\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n pillar, errors = self.ext_pillar(pillar, errors=errors)\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n errors.extend(top_errors)\n if self.opts.get('pillar_opts', False):\n mopts = dict(self.opts)\n if 'grains' in mopts:\n mopts.pop('grains')\n mopts['saltversion'] = __version__\n pillar['master'] = mopts\n if 'pillar' in self.opts and self.opts.get('ssh_merge_pillar', False):\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n if errors:\n for error in errors:\n log.critical('Pillar render error: %s', error)\n pillar['_errors'] = errors\n\n if self.pillar_override:\n pillar = merge(\n pillar,\n self.pillar_override,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n\n decrypt_errors = self.decrypt_pillar(pillar)\n if decrypt_errors:\n pillar.setdefault('_errors', []).extend(decrypt_errors)\n\n return pillar\n" ]
# -*- coding: utf-8 -*- ''' Copy pillar data from a bucket in Amazon S3 The S3 pillar can be configured in the master config file with the following options .. code-block:: yaml ext_pillar: - s3: bucket: my.fancy.pillar.bucket keyid: KASKFJWAKJASJKDAJKSD key: ksladfDLKDALSFKSD93q032sdDasdfasdflsadkf multiple_env: False environment: base prefix: somewhere/overthere verify_ssl: True service_url: s3.amazonaws.com kms_keyid: 01234567-89ab-cdef-0123-4567890abcde s3_cache_expire: 30 s3_sync_on_update: True path_style: False https_enable: True The ``bucket`` parameter specifies the target S3 bucket. It is required. The ``keyid`` parameter specifies the key id to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``key`` parameter specifies the key to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``multiple_env`` defaults to False. It specifies whether the pillar should interpret top level folders as pillar environments (see mode section below). The ``environment`` defaults to 'base'. It specifies which environment the bucket represents when in single environments mode (see mode section below). It is ignored if multiple_env is True. The ``prefix`` defaults to ''. It specifies a key prefix to use when searching for data in the bucket for the pillar. It works when multiple_env is True or False. Essentially it tells ext_pillar to look for your pillar data in a 'subdirectory' of your S3 bucket The ``verify_ssl`` parameter defaults to True. It specifies whether to check for valid S3 SSL certificates. *NOTE* If you use bucket names with periods, this must be set to False else an invalid certificate error will be thrown (issue #12200). The ``service_url`` parameter defaults to 's3.amazonaws.com'. It specifies the base url to use for accessing S3. The ``kms_keyid`` parameter is optional. It specifies the ID of the Key Management Service (KMS) master key that was used to encrypt the object. The ``s3_cache_expire`` parameter defaults to 30s. It specifies expiration time of S3 metadata cache file. The ``s3_sync_on_update`` parameter defaults to True. It specifies if cache is synced on update rather than jit. The ``path_style`` parameter defaults to False. It specifies whether to use path style requests or dns style requests The ``https_enable`` parameter defaults to True. It specifies whether to use https protocol or http protocol This pillar can operate in two modes, single environment per bucket or multiple environments per bucket. Single environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<files> Multiple environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<environment>/<files> If you wish to define your pillar data entirely within S3 it's recommended that you use the `prefix=` parameter and specify one entry in ext_pillar for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time import pickle from copy import deepcopy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import filter from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs from salt.pillar import Pillar import salt.utils.files import salt.utils.hashutils # Set up logging log = logging.getLogger(__name__) class S3Credentials(object): def __init__(self, key, keyid, bucket, service_url, verify_ssl=True, kms_keyid=None, location=None, path_style=False, https_enable=True): self.key = key self.keyid = keyid self.kms_keyid = kms_keyid self.bucket = bucket self.service_url = service_url self.verify_ssl = verify_ssl self.location = location self.path_style = path_style self.https_enable = https_enable 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 _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_cached_file_name(bucket, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path 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 _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 _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 _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_file_meta(metadata, bucket, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = env_meta[bucket] if bucket in env_meta else {} files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: return item_meta 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 )
saltstack/salt
salt/pillar/s3.py
_init
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
Connect to S3 and download the metadata for each file in all buckets specified and cache the data to disk.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L192-L225
null
# -*- coding: utf-8 -*- ''' Copy pillar data from a bucket in Amazon S3 The S3 pillar can be configured in the master config file with the following options .. code-block:: yaml ext_pillar: - s3: bucket: my.fancy.pillar.bucket keyid: KASKFJWAKJASJKDAJKSD key: ksladfDLKDALSFKSD93q032sdDasdfasdflsadkf multiple_env: False environment: base prefix: somewhere/overthere verify_ssl: True service_url: s3.amazonaws.com kms_keyid: 01234567-89ab-cdef-0123-4567890abcde s3_cache_expire: 30 s3_sync_on_update: True path_style: False https_enable: True The ``bucket`` parameter specifies the target S3 bucket. It is required. The ``keyid`` parameter specifies the key id to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``key`` parameter specifies the key to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``multiple_env`` defaults to False. It specifies whether the pillar should interpret top level folders as pillar environments (see mode section below). The ``environment`` defaults to 'base'. It specifies which environment the bucket represents when in single environments mode (see mode section below). It is ignored if multiple_env is True. The ``prefix`` defaults to ''. It specifies a key prefix to use when searching for data in the bucket for the pillar. It works when multiple_env is True or False. Essentially it tells ext_pillar to look for your pillar data in a 'subdirectory' of your S3 bucket The ``verify_ssl`` parameter defaults to True. It specifies whether to check for valid S3 SSL certificates. *NOTE* If you use bucket names with periods, this must be set to False else an invalid certificate error will be thrown (issue #12200). The ``service_url`` parameter defaults to 's3.amazonaws.com'. It specifies the base url to use for accessing S3. The ``kms_keyid`` parameter is optional. It specifies the ID of the Key Management Service (KMS) master key that was used to encrypt the object. The ``s3_cache_expire`` parameter defaults to 30s. It specifies expiration time of S3 metadata cache file. The ``s3_sync_on_update`` parameter defaults to True. It specifies if cache is synced on update rather than jit. The ``path_style`` parameter defaults to False. It specifies whether to use path style requests or dns style requests The ``https_enable`` parameter defaults to True. It specifies whether to use https protocol or http protocol This pillar can operate in two modes, single environment per bucket or multiple environments per bucket. Single environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<files> Multiple environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<environment>/<files> If you wish to define your pillar data entirely within S3 it's recommended that you use the `prefix=` parameter and specify one entry in ext_pillar for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time import pickle from copy import deepcopy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import filter from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs from salt.pillar import Pillar import salt.utils.files import salt.utils.hashutils # Set up logging log = logging.getLogger(__name__) class S3Credentials(object): def __init__(self, key, keyid, bucket, service_url, verify_ssl=True, kms_keyid=None, location=None, path_style=False, https_enable=True): self.key = key self.keyid = keyid self.kms_keyid = kms_keyid self.bucket = bucket self.service_url = service_url self.verify_ssl = verify_ssl self.location = location self.path_style = path_style self.https_enable = https_enable 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 _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_cached_file_name(bucket, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path 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 _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 _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 _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_file_meta(metadata, bucket, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = env_meta[bucket] if bucket in env_meta else {} files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: return item_meta 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 )
saltstack/salt
salt/pillar/s3.py
_get_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
Get pillar cache directory. Initialize it if it does not exist.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L228-L239
null
# -*- coding: utf-8 -*- ''' Copy pillar data from a bucket in Amazon S3 The S3 pillar can be configured in the master config file with the following options .. code-block:: yaml ext_pillar: - s3: bucket: my.fancy.pillar.bucket keyid: KASKFJWAKJASJKDAJKSD key: ksladfDLKDALSFKSD93q032sdDasdfasdflsadkf multiple_env: False environment: base prefix: somewhere/overthere verify_ssl: True service_url: s3.amazonaws.com kms_keyid: 01234567-89ab-cdef-0123-4567890abcde s3_cache_expire: 30 s3_sync_on_update: True path_style: False https_enable: True The ``bucket`` parameter specifies the target S3 bucket. It is required. The ``keyid`` parameter specifies the key id to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``key`` parameter specifies the key to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``multiple_env`` defaults to False. It specifies whether the pillar should interpret top level folders as pillar environments (see mode section below). The ``environment`` defaults to 'base'. It specifies which environment the bucket represents when in single environments mode (see mode section below). It is ignored if multiple_env is True. The ``prefix`` defaults to ''. It specifies a key prefix to use when searching for data in the bucket for the pillar. It works when multiple_env is True or False. Essentially it tells ext_pillar to look for your pillar data in a 'subdirectory' of your S3 bucket The ``verify_ssl`` parameter defaults to True. It specifies whether to check for valid S3 SSL certificates. *NOTE* If you use bucket names with periods, this must be set to False else an invalid certificate error will be thrown (issue #12200). The ``service_url`` parameter defaults to 's3.amazonaws.com'. It specifies the base url to use for accessing S3. The ``kms_keyid`` parameter is optional. It specifies the ID of the Key Management Service (KMS) master key that was used to encrypt the object. The ``s3_cache_expire`` parameter defaults to 30s. It specifies expiration time of S3 metadata cache file. The ``s3_sync_on_update`` parameter defaults to True. It specifies if cache is synced on update rather than jit. The ``path_style`` parameter defaults to False. It specifies whether to use path style requests or dns style requests The ``https_enable`` parameter defaults to True. It specifies whether to use https protocol or http protocol This pillar can operate in two modes, single environment per bucket or multiple environments per bucket. Single environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<files> Multiple environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<environment>/<files> If you wish to define your pillar data entirely within S3 it's recommended that you use the `prefix=` parameter and specify one entry in ext_pillar for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time import pickle from copy import deepcopy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import filter from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs from salt.pillar import Pillar import salt.utils.files import salt.utils.hashutils # Set up logging log = logging.getLogger(__name__) class S3Credentials(object): def __init__(self, key, keyid, bucket, service_url, verify_ssl=True, kms_keyid=None, location=None, path_style=False, https_enable=True): self.key = key self.keyid = keyid self.kms_keyid = kms_keyid self.bucket = bucket self.service_url = service_url self.verify_ssl = verify_ssl self.location = location self.path_style = path_style self.https_enable = https_enable 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 _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 _get_cached_file_name(bucket, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path 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 _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 _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 _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_file_meta(metadata, bucket, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = env_meta[bucket] if bucket in env_meta else {} files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: return item_meta 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 )
saltstack/salt
salt/pillar/s3.py
_get_buckets_cache_filename
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))
Return the filename of the cache for bucket contents. Create the path if it does not exist.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L256-L266
null
# -*- coding: utf-8 -*- ''' Copy pillar data from a bucket in Amazon S3 The S3 pillar can be configured in the master config file with the following options .. code-block:: yaml ext_pillar: - s3: bucket: my.fancy.pillar.bucket keyid: KASKFJWAKJASJKDAJKSD key: ksladfDLKDALSFKSD93q032sdDasdfasdflsadkf multiple_env: False environment: base prefix: somewhere/overthere verify_ssl: True service_url: s3.amazonaws.com kms_keyid: 01234567-89ab-cdef-0123-4567890abcde s3_cache_expire: 30 s3_sync_on_update: True path_style: False https_enable: True The ``bucket`` parameter specifies the target S3 bucket. It is required. The ``keyid`` parameter specifies the key id to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``key`` parameter specifies the key to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``multiple_env`` defaults to False. It specifies whether the pillar should interpret top level folders as pillar environments (see mode section below). The ``environment`` defaults to 'base'. It specifies which environment the bucket represents when in single environments mode (see mode section below). It is ignored if multiple_env is True. The ``prefix`` defaults to ''. It specifies a key prefix to use when searching for data in the bucket for the pillar. It works when multiple_env is True or False. Essentially it tells ext_pillar to look for your pillar data in a 'subdirectory' of your S3 bucket The ``verify_ssl`` parameter defaults to True. It specifies whether to check for valid S3 SSL certificates. *NOTE* If you use bucket names with periods, this must be set to False else an invalid certificate error will be thrown (issue #12200). The ``service_url`` parameter defaults to 's3.amazonaws.com'. It specifies the base url to use for accessing S3. The ``kms_keyid`` parameter is optional. It specifies the ID of the Key Management Service (KMS) master key that was used to encrypt the object. The ``s3_cache_expire`` parameter defaults to 30s. It specifies expiration time of S3 metadata cache file. The ``s3_sync_on_update`` parameter defaults to True. It specifies if cache is synced on update rather than jit. The ``path_style`` parameter defaults to False. It specifies whether to use path style requests or dns style requests The ``https_enable`` parameter defaults to True. It specifies whether to use https protocol or http protocol This pillar can operate in two modes, single environment per bucket or multiple environments per bucket. Single environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<files> Multiple environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<environment>/<files> If you wish to define your pillar data entirely within S3 it's recommended that you use the `prefix=` parameter and specify one entry in ext_pillar for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time import pickle from copy import deepcopy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import filter from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs from salt.pillar import Pillar import salt.utils.files import salt.utils.hashutils # Set up logging log = logging.getLogger(__name__) class S3Credentials(object): def __init__(self, key, keyid, bucket, service_url, verify_ssl=True, kms_keyid=None, location=None, path_style=False, https_enable=True): self.key = key self.keyid = keyid self.kms_keyid = kms_keyid self.bucket = bucket self.service_url = service_url self.verify_ssl = verify_ssl self.location = location self.path_style = path_style self.https_enable = https_enable 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 _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 _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_cached_file_name(bucket, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path 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 _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 _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_file_meta(metadata, bucket, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = env_meta[bucket] if bucket in env_meta else {} files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: return item_meta 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 )
saltstack/salt
salt/pillar/s3.py
_refresh_buckets_cache_file
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
Retrieve the content of all buckets and cache the metadata to the buckets cache file
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L269-L349
null
# -*- coding: utf-8 -*- ''' Copy pillar data from a bucket in Amazon S3 The S3 pillar can be configured in the master config file with the following options .. code-block:: yaml ext_pillar: - s3: bucket: my.fancy.pillar.bucket keyid: KASKFJWAKJASJKDAJKSD key: ksladfDLKDALSFKSD93q032sdDasdfasdflsadkf multiple_env: False environment: base prefix: somewhere/overthere verify_ssl: True service_url: s3.amazonaws.com kms_keyid: 01234567-89ab-cdef-0123-4567890abcde s3_cache_expire: 30 s3_sync_on_update: True path_style: False https_enable: True The ``bucket`` parameter specifies the target S3 bucket. It is required. The ``keyid`` parameter specifies the key id to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``key`` parameter specifies the key to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``multiple_env`` defaults to False. It specifies whether the pillar should interpret top level folders as pillar environments (see mode section below). The ``environment`` defaults to 'base'. It specifies which environment the bucket represents when in single environments mode (see mode section below). It is ignored if multiple_env is True. The ``prefix`` defaults to ''. It specifies a key prefix to use when searching for data in the bucket for the pillar. It works when multiple_env is True or False. Essentially it tells ext_pillar to look for your pillar data in a 'subdirectory' of your S3 bucket The ``verify_ssl`` parameter defaults to True. It specifies whether to check for valid S3 SSL certificates. *NOTE* If you use bucket names with periods, this must be set to False else an invalid certificate error will be thrown (issue #12200). The ``service_url`` parameter defaults to 's3.amazonaws.com'. It specifies the base url to use for accessing S3. The ``kms_keyid`` parameter is optional. It specifies the ID of the Key Management Service (KMS) master key that was used to encrypt the object. The ``s3_cache_expire`` parameter defaults to 30s. It specifies expiration time of S3 metadata cache file. The ``s3_sync_on_update`` parameter defaults to True. It specifies if cache is synced on update rather than jit. The ``path_style`` parameter defaults to False. It specifies whether to use path style requests or dns style requests The ``https_enable`` parameter defaults to True. It specifies whether to use https protocol or http protocol This pillar can operate in two modes, single environment per bucket or multiple environments per bucket. Single environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<files> Multiple environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<environment>/<files> If you wish to define your pillar data entirely within S3 it's recommended that you use the `prefix=` parameter and specify one entry in ext_pillar for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time import pickle from copy import deepcopy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import filter from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs from salt.pillar import Pillar import salt.utils.files import salt.utils.hashutils # Set up logging log = logging.getLogger(__name__) class S3Credentials(object): def __init__(self, key, keyid, bucket, service_url, verify_ssl=True, kms_keyid=None, location=None, path_style=False, https_enable=True): self.key = key self.keyid = keyid self.kms_keyid = kms_keyid self.bucket = bucket self.service_url = service_url self.verify_ssl = verify_ssl self.location = location self.path_style = path_style self.https_enable = https_enable 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 _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 _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_cached_file_name(bucket, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path 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 _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 _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_file_meta(metadata, bucket, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = env_meta[bucket] if bucket in env_meta else {} files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: return item_meta 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 )
saltstack/salt
salt/pillar/s3.py
_read_buckets_cache_file
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
Return the contents of the buckets cache file
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L352-L362
null
# -*- coding: utf-8 -*- ''' Copy pillar data from a bucket in Amazon S3 The S3 pillar can be configured in the master config file with the following options .. code-block:: yaml ext_pillar: - s3: bucket: my.fancy.pillar.bucket keyid: KASKFJWAKJASJKDAJKSD key: ksladfDLKDALSFKSD93q032sdDasdfasdflsadkf multiple_env: False environment: base prefix: somewhere/overthere verify_ssl: True service_url: s3.amazonaws.com kms_keyid: 01234567-89ab-cdef-0123-4567890abcde s3_cache_expire: 30 s3_sync_on_update: True path_style: False https_enable: True The ``bucket`` parameter specifies the target S3 bucket. It is required. The ``keyid`` parameter specifies the key id to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``key`` parameter specifies the key to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``multiple_env`` defaults to False. It specifies whether the pillar should interpret top level folders as pillar environments (see mode section below). The ``environment`` defaults to 'base'. It specifies which environment the bucket represents when in single environments mode (see mode section below). It is ignored if multiple_env is True. The ``prefix`` defaults to ''. It specifies a key prefix to use when searching for data in the bucket for the pillar. It works when multiple_env is True or False. Essentially it tells ext_pillar to look for your pillar data in a 'subdirectory' of your S3 bucket The ``verify_ssl`` parameter defaults to True. It specifies whether to check for valid S3 SSL certificates. *NOTE* If you use bucket names with periods, this must be set to False else an invalid certificate error will be thrown (issue #12200). The ``service_url`` parameter defaults to 's3.amazonaws.com'. It specifies the base url to use for accessing S3. The ``kms_keyid`` parameter is optional. It specifies the ID of the Key Management Service (KMS) master key that was used to encrypt the object. The ``s3_cache_expire`` parameter defaults to 30s. It specifies expiration time of S3 metadata cache file. The ``s3_sync_on_update`` parameter defaults to True. It specifies if cache is synced on update rather than jit. The ``path_style`` parameter defaults to False. It specifies whether to use path style requests or dns style requests The ``https_enable`` parameter defaults to True. It specifies whether to use https protocol or http protocol This pillar can operate in two modes, single environment per bucket or multiple environments per bucket. Single environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<files> Multiple environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<environment>/<files> If you wish to define your pillar data entirely within S3 it's recommended that you use the `prefix=` parameter and specify one entry in ext_pillar for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time import pickle from copy import deepcopy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import filter from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs from salt.pillar import Pillar import salt.utils.files import salt.utils.hashutils # Set up logging log = logging.getLogger(__name__) class S3Credentials(object): def __init__(self, key, keyid, bucket, service_url, verify_ssl=True, kms_keyid=None, location=None, path_style=False, https_enable=True): self.key = key self.keyid = keyid self.kms_keyid = kms_keyid self.bucket = bucket self.service_url = service_url self.verify_ssl = verify_ssl self.location = location self.path_style = path_style self.https_enable = https_enable 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 _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 _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_cached_file_name(bucket, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path 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 _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 _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_file_meta(metadata, bucket, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = env_meta[bucket] if bucket in env_meta else {} files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: return item_meta 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 )
saltstack/salt
salt/pillar/s3.py
_find_files
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
Looks for all the files in the S3 bucket cache metadata
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L365-L381
null
# -*- coding: utf-8 -*- ''' Copy pillar data from a bucket in Amazon S3 The S3 pillar can be configured in the master config file with the following options .. code-block:: yaml ext_pillar: - s3: bucket: my.fancy.pillar.bucket keyid: KASKFJWAKJASJKDAJKSD key: ksladfDLKDALSFKSD93q032sdDasdfasdflsadkf multiple_env: False environment: base prefix: somewhere/overthere verify_ssl: True service_url: s3.amazonaws.com kms_keyid: 01234567-89ab-cdef-0123-4567890abcde s3_cache_expire: 30 s3_sync_on_update: True path_style: False https_enable: True The ``bucket`` parameter specifies the target S3 bucket. It is required. The ``keyid`` parameter specifies the key id to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``key`` parameter specifies the key to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``multiple_env`` defaults to False. It specifies whether the pillar should interpret top level folders as pillar environments (see mode section below). The ``environment`` defaults to 'base'. It specifies which environment the bucket represents when in single environments mode (see mode section below). It is ignored if multiple_env is True. The ``prefix`` defaults to ''. It specifies a key prefix to use when searching for data in the bucket for the pillar. It works when multiple_env is True or False. Essentially it tells ext_pillar to look for your pillar data in a 'subdirectory' of your S3 bucket The ``verify_ssl`` parameter defaults to True. It specifies whether to check for valid S3 SSL certificates. *NOTE* If you use bucket names with periods, this must be set to False else an invalid certificate error will be thrown (issue #12200). The ``service_url`` parameter defaults to 's3.amazonaws.com'. It specifies the base url to use for accessing S3. The ``kms_keyid`` parameter is optional. It specifies the ID of the Key Management Service (KMS) master key that was used to encrypt the object. The ``s3_cache_expire`` parameter defaults to 30s. It specifies expiration time of S3 metadata cache file. The ``s3_sync_on_update`` parameter defaults to True. It specifies if cache is synced on update rather than jit. The ``path_style`` parameter defaults to False. It specifies whether to use path style requests or dns style requests The ``https_enable`` parameter defaults to True. It specifies whether to use https protocol or http protocol This pillar can operate in two modes, single environment per bucket or multiple environments per bucket. Single environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<files> Multiple environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<environment>/<files> If you wish to define your pillar data entirely within S3 it's recommended that you use the `prefix=` parameter and specify one entry in ext_pillar for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time import pickle from copy import deepcopy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import filter from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs from salt.pillar import Pillar import salt.utils.files import salt.utils.hashutils # Set up logging log = logging.getLogger(__name__) class S3Credentials(object): def __init__(self, key, keyid, bucket, service_url, verify_ssl=True, kms_keyid=None, location=None, path_style=False, https_enable=True): self.key = key self.keyid = keyid self.kms_keyid = kms_keyid self.bucket = bucket self.service_url = service_url self.verify_ssl = verify_ssl self.location = location self.path_style = path_style self.https_enable = https_enable 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 _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 _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_cached_file_name(bucket, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path 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 _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 _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 _find_file_meta(metadata, bucket, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = env_meta[bucket] if bucket in env_meta else {} files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: return item_meta 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 )
saltstack/salt
salt/pillar/s3.py
_get_file_from_s3
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 )
Checks the local cache for the file, if it's old or missing go grab the file from S3 and update the cache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/s3.py#L398-L432
null
# -*- coding: utf-8 -*- ''' Copy pillar data from a bucket in Amazon S3 The S3 pillar can be configured in the master config file with the following options .. code-block:: yaml ext_pillar: - s3: bucket: my.fancy.pillar.bucket keyid: KASKFJWAKJASJKDAJKSD key: ksladfDLKDALSFKSD93q032sdDasdfasdflsadkf multiple_env: False environment: base prefix: somewhere/overthere verify_ssl: True service_url: s3.amazonaws.com kms_keyid: 01234567-89ab-cdef-0123-4567890abcde s3_cache_expire: 30 s3_sync_on_update: True path_style: False https_enable: True The ``bucket`` parameter specifies the target S3 bucket. It is required. The ``keyid`` parameter specifies the key id to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``key`` parameter specifies the key to use when access the S3 bucket. If it is not provided, an attempt to fetch it from EC2 instance meta-data will be made. The ``multiple_env`` defaults to False. It specifies whether the pillar should interpret top level folders as pillar environments (see mode section below). The ``environment`` defaults to 'base'. It specifies which environment the bucket represents when in single environments mode (see mode section below). It is ignored if multiple_env is True. The ``prefix`` defaults to ''. It specifies a key prefix to use when searching for data in the bucket for the pillar. It works when multiple_env is True or False. Essentially it tells ext_pillar to look for your pillar data in a 'subdirectory' of your S3 bucket The ``verify_ssl`` parameter defaults to True. It specifies whether to check for valid S3 SSL certificates. *NOTE* If you use bucket names with periods, this must be set to False else an invalid certificate error will be thrown (issue #12200). The ``service_url`` parameter defaults to 's3.amazonaws.com'. It specifies the base url to use for accessing S3. The ``kms_keyid`` parameter is optional. It specifies the ID of the Key Management Service (KMS) master key that was used to encrypt the object. The ``s3_cache_expire`` parameter defaults to 30s. It specifies expiration time of S3 metadata cache file. The ``s3_sync_on_update`` parameter defaults to True. It specifies if cache is synced on update rather than jit. The ``path_style`` parameter defaults to False. It specifies whether to use path style requests or dns style requests The ``https_enable`` parameter defaults to True. It specifies whether to use https protocol or http protocol This pillar can operate in two modes, single environment per bucket or multiple environments per bucket. Single environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<files> Multiple environment mode must have this bucket structure: .. code-block:: text s3://<bucket name>/<prefix>/<environment>/<files> If you wish to define your pillar data entirely within S3 it's recommended that you use the `prefix=` parameter and specify one entry in ext_pillar for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time import pickle from copy import deepcopy # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext import six from salt.ext.six.moves import filter from salt.ext.six.moves.urllib.parse import quote as _quote # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import salt libs from salt.pillar import Pillar import salt.utils.files import salt.utils.hashutils # Set up logging log = logging.getLogger(__name__) class S3Credentials(object): def __init__(self, key, keyid, bucket, service_url, verify_ssl=True, kms_keyid=None, location=None, path_style=False, https_enable=True): self.key = key self.keyid = keyid self.kms_keyid = kms_keyid self.bucket = bucket self.service_url = service_url self.verify_ssl = verify_ssl self.location = location self.path_style = path_style self.https_enable = https_enable 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 _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 _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_cached_file_name(bucket, saltenv, path): ''' Return the cached file name for a bucket path file ''' file_path = os.path.join(_get_cache_dir(), saltenv, bucket, path) # make sure bucket and saltenv directories exist if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) return file_path 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 _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 _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 _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_file_meta(metadata, bucket, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = env_meta[bucket] if bucket in env_meta else {} files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta))) for item_meta in files_meta: if 'Key' in item_meta and item_meta['Key'] == path: return item_meta
saltstack/salt
salt/modules/logadm.py
_arg2opt
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
Turn a pass argument into the correct option
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L61-L67
null
# -*- coding: utf-8 -*- ''' Module for managing Solaris logadm based log rotations. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import shlex try: from shlex import quote as _quote_args # pylint: disable=E0611 except ImportError: from pipes import quote as _quote_args # Import salt libs from salt.ext import six import salt.utils.args import salt.utils.decorators as decorators import salt.utils.files import salt.utils.stringutils log = logging.getLogger(__name__) default_conf = '/etc/logadm.conf' option_toggles = { '-c': 'copy', '-l': 'localtime', '-N': 'skip_missing', } option_flags = { '-A': 'age', '-C': 'count', '-a': 'post_command', '-b': 'pre_command', '-e': 'mail_addr', '-E': 'expire_command', '-g': 'group', '-m': 'mode', '-M': 'rename_command', '-o': 'owner', '-p': 'period', '-P': 'timestmp', '-R': 'old_created_command', '-s': 'size', '-S': 'max_size', '-t': 'template', '-T': 'old_pattern', '-w': 'entryname', '-z': 'compress_count', } def __virtual__(): ''' Only work on Solaris based systems ''' if 'Solaris' in __grains__['os_family']: return True return (False, 'The logadm execution module cannot be loaded: only available on Solaris.') 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_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 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 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 @decorators.memoize 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 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 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')
saltstack/salt
salt/modules/logadm.py
_parse_conf
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
Parse a logadm configuration file.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L70-L84
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# -*- coding: utf-8 -*- ''' Module for managing Solaris logadm based log rotations. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import shlex try: from shlex import quote as _quote_args # pylint: disable=E0611 except ImportError: from pipes import quote as _quote_args # Import salt libs from salt.ext import six import salt.utils.args import salt.utils.decorators as decorators import salt.utils.files import salt.utils.stringutils log = logging.getLogger(__name__) default_conf = '/etc/logadm.conf' option_toggles = { '-c': 'copy', '-l': 'localtime', '-N': 'skip_missing', } option_flags = { '-A': 'age', '-C': 'count', '-a': 'post_command', '-b': 'pre_command', '-e': 'mail_addr', '-E': 'expire_command', '-g': 'group', '-m': 'mode', '-M': 'rename_command', '-o': 'owner', '-p': 'period', '-P': 'timestmp', '-R': 'old_created_command', '-s': 'size', '-S': 'max_size', '-t': 'template', '-T': 'old_pattern', '-w': 'entryname', '-z': 'compress_count', } def __virtual__(): ''' Only work on Solaris based systems ''' if 'Solaris' in __grains__['os_family']: return True return (False, 'The logadm execution module cannot be loaded: only available on Solaris.') 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 _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 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 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 @decorators.memoize 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 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 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')
saltstack/salt
salt/modules/logadm.py
_parse_options
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
Parse a logadm options string
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L87-L152
null
# -*- coding: utf-8 -*- ''' Module for managing Solaris logadm based log rotations. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import shlex try: from shlex import quote as _quote_args # pylint: disable=E0611 except ImportError: from pipes import quote as _quote_args # Import salt libs from salt.ext import six import salt.utils.args import salt.utils.decorators as decorators import salt.utils.files import salt.utils.stringutils log = logging.getLogger(__name__) default_conf = '/etc/logadm.conf' option_toggles = { '-c': 'copy', '-l': 'localtime', '-N': 'skip_missing', } option_flags = { '-A': 'age', '-C': 'count', '-a': 'post_command', '-b': 'pre_command', '-e': 'mail_addr', '-E': 'expire_command', '-g': 'group', '-m': 'mode', '-M': 'rename_command', '-o': 'owner', '-p': 'period', '-P': 'timestmp', '-R': 'old_created_command', '-s': 'size', '-S': 'max_size', '-t': 'template', '-T': 'old_pattern', '-w': 'entryname', '-z': 'compress_count', } def __virtual__(): ''' Only work on Solaris based systems ''' if 'Solaris' in __grains__['os_family']: return True return (False, 'The logadm execution module cannot be loaded: only available on Solaris.') 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 _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 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 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 @decorators.memoize 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 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 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')
saltstack/salt
salt/modules/logadm.py
show_conf
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L155-L179
[ "def _parse_conf(conf_file=default_conf):\n '''\n Parse a logadm configuration file.\n '''\n ret = {}\n with salt.utils.files.fopen(conf_file, 'r') as ifile:\n for line in ifile:\n line = salt.utils.stringutils.to_unicode(line).strip()\n if not line:\n continue\n if line.startswith('#'):\n continue\n splitline = line.split(' ', 1)\n ret[splitline[0]] = splitline[1]\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing Solaris logadm based log rotations. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import shlex try: from shlex import quote as _quote_args # pylint: disable=E0611 except ImportError: from pipes import quote as _quote_args # Import salt libs from salt.ext import six import salt.utils.args import salt.utils.decorators as decorators import salt.utils.files import salt.utils.stringutils log = logging.getLogger(__name__) default_conf = '/etc/logadm.conf' option_toggles = { '-c': 'copy', '-l': 'localtime', '-N': 'skip_missing', } option_flags = { '-A': 'age', '-C': 'count', '-a': 'post_command', '-b': 'pre_command', '-e': 'mail_addr', '-E': 'expire_command', '-g': 'group', '-m': 'mode', '-M': 'rename_command', '-o': 'owner', '-p': 'period', '-P': 'timestmp', '-R': 'old_created_command', '-s': 'size', '-S': 'max_size', '-t': 'template', '-T': 'old_pattern', '-w': 'entryname', '-z': 'compress_count', } def __virtual__(): ''' Only work on Solaris based systems ''' if 'Solaris' in __grains__['os_family']: return True return (False, 'The logadm execution module cannot be loaded: only available on Solaris.') 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 _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_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 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 @decorators.memoize 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 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 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')
saltstack/salt
salt/modules/logadm.py
list_conf
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L182-L217
[ "def _parse_conf(conf_file=default_conf):\n '''\n Parse a logadm configuration file.\n '''\n ret = {}\n with salt.utils.files.fopen(conf_file, 'r') as ifile:\n for line in ifile:\n line = salt.utils.stringutils.to_unicode(line).strip()\n if not line:\n continue\n if line.startswith('#'):\n continue\n splitline = line.split(' ', 1)\n ret[splitline[0]] = splitline[1]\n return ret\n", "def _parse_options(entry, options, include_unset=True):\n '''\n Parse a logadm options string\n '''\n log_cfg = {}\n options = shlex.split(options)\n if not options:\n return None\n\n ## identifier is entry or log?\n if entry.startswith('/'):\n log_cfg['log_file'] = entry\n else:\n log_cfg['entryname'] = entry\n\n ## parse options\n # NOTE: we loop over the options because values may exist multiple times\n index = 0\n while index < len(options):\n # log file\n if index in [0, (len(options)-1)] and options[index].startswith('/'):\n log_cfg['log_file'] = options[index]\n\n # check if toggle option\n elif options[index] in option_toggles:\n log_cfg[option_toggles[options[index]]] = True\n\n # check if flag option\n elif options[index] in option_flags and (index+1) <= len(options):\n log_cfg[option_flags[options[index]]] = int(options[index+1]) if options[index+1].isdigit() else options[index+1]\n index += 1\n\n # unknown options\n else:\n if 'additional_options' not in log_cfg:\n log_cfg['additional_options'] = []\n if ' ' in options[index]:\n log_cfg['dditional_options'] = \"'{}'\".format(options[index])\n else:\n log_cfg['additional_options'].append(options[index])\n\n index += 1\n\n ## turn additional_options into string\n if 'additional_options' in log_cfg:\n log_cfg['additional_options'] = \" \".join(log_cfg['additional_options'])\n\n ## ensure we have a log_file\n # NOTE: logadm assumes logname is a file if no log_file is given\n if 'log_file' not in log_cfg and 'entryname' in log_cfg:\n log_cfg['log_file'] = log_cfg['entryname']\n del log_cfg['entryname']\n\n ## include unset\n if include_unset:\n # toggle optioons\n for name in option_toggles.values():\n if name not in log_cfg:\n log_cfg[name] = False\n\n # flag options\n for name in option_flags.values():\n if name not in log_cfg:\n log_cfg[name] = None\n\n return log_cfg\n" ]
# -*- coding: utf-8 -*- ''' Module for managing Solaris logadm based log rotations. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import shlex try: from shlex import quote as _quote_args # pylint: disable=E0611 except ImportError: from pipes import quote as _quote_args # Import salt libs from salt.ext import six import salt.utils.args import salt.utils.decorators as decorators import salt.utils.files import salt.utils.stringutils log = logging.getLogger(__name__) default_conf = '/etc/logadm.conf' option_toggles = { '-c': 'copy', '-l': 'localtime', '-N': 'skip_missing', } option_flags = { '-A': 'age', '-C': 'count', '-a': 'post_command', '-b': 'pre_command', '-e': 'mail_addr', '-E': 'expire_command', '-g': 'group', '-m': 'mode', '-M': 'rename_command', '-o': 'owner', '-p': 'period', '-P': 'timestmp', '-R': 'old_created_command', '-s': 'size', '-S': 'max_size', '-t': 'template', '-T': 'old_pattern', '-w': 'entryname', '-z': 'compress_count', } def __virtual__(): ''' Only work on Solaris based systems ''' if 'Solaris' in __grains__['os_family']: return True return (False, 'The logadm execution module cannot be loaded: only available on Solaris.') 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 _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_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 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 @decorators.memoize 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 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 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')
saltstack/salt
salt/modules/logadm.py
show_args
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
Show which arguments map to which flags and options. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' logadm.show_args
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L221-L239
null
# -*- coding: utf-8 -*- ''' Module for managing Solaris logadm based log rotations. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import shlex try: from shlex import quote as _quote_args # pylint: disable=E0611 except ImportError: from pipes import quote as _quote_args # Import salt libs from salt.ext import six import salt.utils.args import salt.utils.decorators as decorators import salt.utils.files import salt.utils.stringutils log = logging.getLogger(__name__) default_conf = '/etc/logadm.conf' option_toggles = { '-c': 'copy', '-l': 'localtime', '-N': 'skip_missing', } option_flags = { '-A': 'age', '-C': 'count', '-a': 'post_command', '-b': 'pre_command', '-e': 'mail_addr', '-E': 'expire_command', '-g': 'group', '-m': 'mode', '-M': 'rename_command', '-o': 'owner', '-p': 'period', '-P': 'timestmp', '-R': 'old_created_command', '-s': 'size', '-S': 'max_size', '-t': 'template', '-T': 'old_pattern', '-w': 'entryname', '-z': 'compress_count', } def __virtual__(): ''' Only work on Solaris based systems ''' if 'Solaris' in __grains__['os_family']: return True return (False, 'The logadm execution module cannot be loaded: only available on Solaris.') 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 _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_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 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 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 @decorators.memoize 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 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')
saltstack/salt
salt/modules/logadm.py
rotate
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')
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'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L242-L323
[ "def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n", "def _arg2opt(arg):\n '''\n Turn a pass argument into the correct option\n '''\n res = [o for o, a in option_toggles.items() if a == arg]\n res += [o for o, a in option_flags.items() if a == arg]\n return res[0] if res else None\n" ]
# -*- coding: utf-8 -*- ''' Module for managing Solaris logadm based log rotations. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import shlex try: from shlex import quote as _quote_args # pylint: disable=E0611 except ImportError: from pipes import quote as _quote_args # Import salt libs from salt.ext import six import salt.utils.args import salt.utils.decorators as decorators import salt.utils.files import salt.utils.stringutils log = logging.getLogger(__name__) default_conf = '/etc/logadm.conf' option_toggles = { '-c': 'copy', '-l': 'localtime', '-N': 'skip_missing', } option_flags = { '-A': 'age', '-C': 'count', '-a': 'post_command', '-b': 'pre_command', '-e': 'mail_addr', '-E': 'expire_command', '-g': 'group', '-m': 'mode', '-M': 'rename_command', '-o': 'owner', '-p': 'period', '-P': 'timestmp', '-R': 'old_created_command', '-s': 'size', '-S': 'max_size', '-t': 'template', '-T': 'old_pattern', '-w': 'entryname', '-z': 'compress_count', } def __virtual__(): ''' Only work on Solaris based systems ''' if 'Solaris' in __grains__['os_family']: return True return (False, 'The logadm execution module cannot be loaded: only available on Solaris.') 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 _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_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 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 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 @decorators.memoize 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 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')
saltstack/salt
salt/modules/logadm.py
remove
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')
Remove log pattern from logadm CLI Example: .. code-block:: bash salt '*' logadm.remove myapplog
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/logadm.py#L326-L343
null
# -*- coding: utf-8 -*- ''' Module for managing Solaris logadm based log rotations. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import shlex try: from shlex import quote as _quote_args # pylint: disable=E0611 except ImportError: from pipes import quote as _quote_args # Import salt libs from salt.ext import six import salt.utils.args import salt.utils.decorators as decorators import salt.utils.files import salt.utils.stringutils log = logging.getLogger(__name__) default_conf = '/etc/logadm.conf' option_toggles = { '-c': 'copy', '-l': 'localtime', '-N': 'skip_missing', } option_flags = { '-A': 'age', '-C': 'count', '-a': 'post_command', '-b': 'pre_command', '-e': 'mail_addr', '-E': 'expire_command', '-g': 'group', '-m': 'mode', '-M': 'rename_command', '-o': 'owner', '-p': 'period', '-P': 'timestmp', '-R': 'old_created_command', '-s': 'size', '-S': 'max_size', '-t': 'template', '-T': 'old_pattern', '-w': 'entryname', '-z': 'compress_count', } def __virtual__(): ''' Only work on Solaris based systems ''' if 'Solaris' in __grains__['os_family']: return True return (False, 'The logadm execution module cannot be loaded: only available on Solaris.') 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 _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_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 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 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 @decorators.memoize 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 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')
saltstack/salt
salt/utils/locales.py
get_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
return a list of string encodings to try
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/locales.py#L16-L33
null
# -*- coding: utf-8 -*- ''' the locale utils used by salt ''' # Import Python libs from __future__ import absolute_import, unicode_literals import sys # Import Salt libs import salt.utils.versions from salt.utils.decorators import memoize as real_memoize @real_memoize def sdecode(string_): salt.utils.versions.warn_until( 'Sodium', 'Use of \'salt.utils.locales.sdecode\' detected. This function ' 'has been replaced by \'salt.utils.data.decode\' as of ' 'Salt 2019.2.0. This warning will be removed in Salt Sodium.', stacklevel=3 ) return salt.utils.data.decode(string_) def sdecode_if_string(value_): salt.utils.versions.warn_until( 'Sodium', 'Use of \'salt.utils.locales.sdecode_if_string\' detected. This ' 'function has been replaced by \'salt.utils.data.decode\' as of ' 'Salt 2019.2.0. This warning will be removed in Salt Sodium.', stacklevel=3 ) return salt.utils.data.decode(value_) 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 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 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)
saltstack/salt
salt/utils/locales.py
split_locale
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
Split a locale specifier. The general format is language[_territory][.codeset][@modifier] [charmap] For example: ca_ES.UTF-8@valencia UTF-8
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/locales.py#L58-L83
[ "def split(st, char):\n '''\n Split a string `st` once by `char`; always return a two-element list\n even if the second element is empty.\n '''\n split_st = st.split(char, 1)\n if len(split_st) == 1:\n split_st.append('')\n return split_st\n" ]
# -*- coding: utf-8 -*- ''' the locale utils used by salt ''' # Import Python libs from __future__ import absolute_import, unicode_literals import sys # Import Salt libs import salt.utils.versions from salt.utils.decorators import memoize as real_memoize @real_memoize 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 sdecode(string_): salt.utils.versions.warn_until( 'Sodium', 'Use of \'salt.utils.locales.sdecode\' detected. This function ' 'has been replaced by \'salt.utils.data.decode\' as of ' 'Salt 2019.2.0. This warning will be removed in Salt Sodium.', stacklevel=3 ) return salt.utils.data.decode(string_) def sdecode_if_string(value_): salt.utils.versions.warn_until( 'Sodium', 'Use of \'salt.utils.locales.sdecode_if_string\' detected. This ' 'function has been replaced by \'salt.utils.data.decode\' as of ' 'Salt 2019.2.0. This warning will be removed in Salt Sodium.', stacklevel=3 ) return salt.utils.data.decode(value_) 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 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)
saltstack/salt
salt/utils/locales.py
join_locale
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
Join a locale specifier split in the format returned by split_locale.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/locales.py#L86-L99
null
# -*- coding: utf-8 -*- ''' the locale utils used by salt ''' # Import Python libs from __future__ import absolute_import, unicode_literals import sys # Import Salt libs import salt.utils.versions from salt.utils.decorators import memoize as real_memoize @real_memoize 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 sdecode(string_): salt.utils.versions.warn_until( 'Sodium', 'Use of \'salt.utils.locales.sdecode\' detected. This function ' 'has been replaced by \'salt.utils.data.decode\' as of ' 'Salt 2019.2.0. This warning will be removed in Salt Sodium.', stacklevel=3 ) return salt.utils.data.decode(string_) def sdecode_if_string(value_): salt.utils.versions.warn_until( 'Sodium', 'Use of \'salt.utils.locales.sdecode_if_string\' detected. This ' 'function has been replaced by \'salt.utils.data.decode\' as of ' 'Salt 2019.2.0. This warning will be removed in Salt Sodium.', stacklevel=3 ) return salt.utils.data.decode(value_) 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 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)
saltstack/salt
salt/utils/locales.py
normalize_locale
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)
Format a locale specifier according to the format returned by `locale -a`.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/locales.py#L102-L110
[ "def split_locale(loc):\n '''\n Split a locale specifier. The general format is\n\n language[_territory][.codeset][@modifier] [charmap]\n\n For example:\n\n ca_ES.UTF-8@valencia UTF-8\n '''\n def split(st, char):\n '''\n Split a string `st` once by `char`; always return a two-element list\n even if the second element is empty.\n '''\n split_st = st.split(char, 1)\n if len(split_st) == 1:\n split_st.append('')\n return split_st\n\n comps = {}\n work_st, comps['charmap'] = split(loc, ' ')\n work_st, comps['modifier'] = split(work_st, '@')\n work_st, comps['codeset'] = split(work_st, '.')\n comps['language'], comps['territory'] = split(work_st, '_')\n return comps\n", "def join_locale(comps):\n '''\n Join a locale specifier split in the format returned by split_locale.\n '''\n loc = comps['language']\n if comps.get('territory'):\n loc += '_' + comps['territory']\n if comps.get('codeset'):\n loc += '.' + comps['codeset']\n if comps.get('modifier'):\n loc += '@' + comps['modifier']\n if comps.get('charmap'):\n loc += ' ' + comps['charmap']\n return loc\n" ]
# -*- coding: utf-8 -*- ''' the locale utils used by salt ''' # Import Python libs from __future__ import absolute_import, unicode_literals import sys # Import Salt libs import salt.utils.versions from salt.utils.decorators import memoize as real_memoize @real_memoize 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 sdecode(string_): salt.utils.versions.warn_until( 'Sodium', 'Use of \'salt.utils.locales.sdecode\' detected. This function ' 'has been replaced by \'salt.utils.data.decode\' as of ' 'Salt 2019.2.0. This warning will be removed in Salt Sodium.', stacklevel=3 ) return salt.utils.data.decode(string_) def sdecode_if_string(value_): salt.utils.versions.warn_until( 'Sodium', 'Use of \'salt.utils.locales.sdecode_if_string\' detected. This ' 'function has been replaced by \'salt.utils.data.decode\' as of ' 'Salt 2019.2.0. This warning will be removed in Salt Sodium.', stacklevel=3 ) return salt.utils.data.decode(value_) 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 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
saltstack/salt
salt/returners/mongo_return.py
_remove_dots
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
Remove dots from the given data structure
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_return.py#L96-L105
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _remove_dots(src):\n '''\n Remove dots from the given data structure\n '''\n output = {}\n for key, val in six.iteritems(src):\n if isinstance(val, dict):\n val = _remove_dots(val)\n output[key.replace('.', '-')] = val\n return output\n" ]
# -*- coding: utf-8 -*- ''' Return data to a mongodb server Required python modules: pymongo This returner will send data from the minions to a MongoDB server. To configure the settings for your MongoDB server, add the following lines to the minion config files. .. code-block:: yaml mongo.db: <database name> mongo.host: <server ip address> mongo.user: <MongoDB username> mongo.password: <MongoDB user password> mongo.port: 27017 Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location. .. code-block:: yaml alternative.mongo.db: <database name> alternative.mongo.host: <server ip address> alternative.mongo.user: <MongoDB username> alternative.mongo.password: <MongoDB user password> alternative.mongo.port: 27017 To use the mongo returner, append '--return mongo' to the salt command. .. code-block:: bash salt '*' test.ping --return mongo_return To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return mongo_return --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # import Salt libs import salt.utils.jid import salt.returners from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion # Import third party libs try: import pymongo PYMONGO_VERSION = _LooseVersion(pymongo.version) HAS_PYMONGO = True except ImportError: HAS_PYMONGO = False log = logging.getLogger(__name__) # Define the module's virtual name # currently only used iby _get_options __virtualname__ = 'mongo' def __virtual__(): if not HAS_PYMONGO: return False, 'Could not import mongo returner; pymongo is not installed.' return 'mongo_return' def _get_options(ret): ''' Get the monogo_return options from salt. ''' attrs = {'host': 'host', 'port': 'port', 'db': 'db', 'user': 'user', 'password': 'password', 'indexes': 'indexes'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) return _options 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 returner(ret): ''' Return data to a mongodb server ''' conn, mdb = _get_conn(ret) col = mdb[ret['id']] if isinstance(ret['return'], dict): back = _remove_dots(ret['return']) else: back = ret['return'] if isinstance(ret, dict): full_ret = _remove_dots(ret) else: full_ret = ret log.debug(back) sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret} if 'out' in ret: sdata['out'] = ret['out'] # save returns in the saltReturns collection in the json format: # { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>, # 'fun': <function>, 'full_ret': <unformatted return with dots removed>} # again we run into the issue with deprecated code from previous versions if PYMONGO_VERSION > _LooseVersion('2.3'): #using .copy() to ensure original data for load is unchanged mdb.saltReturns.insert_one(sdata.copy()) else: mdb.saltReturns.insert(sdata.copy()) 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_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 prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass
saltstack/salt
salt/returners/mongo_return.py
_get_conn
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
Return a mongodb connection object
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_return.py#L127-L165
[ "def _get_options(ret):\n '''\n Get the monogo_return options from salt.\n '''\n attrs = {'host': 'host',\n 'port': 'port',\n 'db': 'db',\n 'user': 'user',\n 'password': 'password',\n 'indexes': 'indexes'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n return _options\n" ]
# -*- coding: utf-8 -*- ''' Return data to a mongodb server Required python modules: pymongo This returner will send data from the minions to a MongoDB server. To configure the settings for your MongoDB server, add the following lines to the minion config files. .. code-block:: yaml mongo.db: <database name> mongo.host: <server ip address> mongo.user: <MongoDB username> mongo.password: <MongoDB user password> mongo.port: 27017 Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location. .. code-block:: yaml alternative.mongo.db: <database name> alternative.mongo.host: <server ip address> alternative.mongo.user: <MongoDB username> alternative.mongo.password: <MongoDB user password> alternative.mongo.port: 27017 To use the mongo returner, append '--return mongo' to the salt command. .. code-block:: bash salt '*' test.ping --return mongo_return To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return mongo_return --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # import Salt libs import salt.utils.jid import salt.returners from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion # Import third party libs try: import pymongo PYMONGO_VERSION = _LooseVersion(pymongo.version) HAS_PYMONGO = True except ImportError: HAS_PYMONGO = False log = logging.getLogger(__name__) # Define the module's virtual name # currently only used iby _get_options __virtualname__ = 'mongo' def __virtual__(): if not HAS_PYMONGO: return False, 'Could not import mongo returner; pymongo is not installed.' return 'mongo_return' 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 _get_options(ret): ''' Get the monogo_return options from salt. ''' attrs = {'host': 'host', 'port': 'port', 'db': 'db', 'user': 'user', 'password': 'password', 'indexes': 'indexes'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) return _options def returner(ret): ''' Return data to a mongodb server ''' conn, mdb = _get_conn(ret) col = mdb[ret['id']] if isinstance(ret['return'], dict): back = _remove_dots(ret['return']) else: back = ret['return'] if isinstance(ret, dict): full_ret = _remove_dots(ret) else: full_ret = ret log.debug(back) sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret} if 'out' in ret: sdata['out'] = ret['out'] # save returns in the saltReturns collection in the json format: # { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>, # 'fun': <function>, 'full_ret': <unformatted return with dots removed>} # again we run into the issue with deprecated code from previous versions if PYMONGO_VERSION > _LooseVersion('2.3'): #using .copy() to ensure original data for load is unchanged mdb.saltReturns.insert_one(sdata.copy()) else: mdb.saltReturns.insert(sdata.copy()) 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_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 prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass
saltstack/salt
salt/returners/mongo_return.py
get_jid
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
Return the return information associated with a jid
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_return.py#L203-L215
[ "def _get_conn(ret):\n '''\n Return a mongodb connection object\n '''\n _options = _get_options(ret)\n\n host = _options.get('host')\n port = _options.get('port')\n db_ = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n indexes = _options.get('indexes', False)\n\n # at some point we should remove support for\n # pymongo versions < 2.3 until then there are\n # a bunch of these sections that need to be supported\n\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n conn = pymongo.MongoClient(host, port)\n else:\n conn = pymongo.Connection(host, port)\n mdb = conn[db_]\n\n if user and password:\n mdb.authenticate(user, password)\n\n if indexes:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n mdb.saltReturns.create_index('minion')\n mdb.saltReturns.create_index('jid')\n\n mdb.jobs.create_index('jid')\n else:\n mdb.saltReturns.ensure_index('minion')\n mdb.saltReturns.ensure_index('jid')\n\n mdb.jobs.ensure_index('jid')\n\n return conn, mdb\n" ]
# -*- coding: utf-8 -*- ''' Return data to a mongodb server Required python modules: pymongo This returner will send data from the minions to a MongoDB server. To configure the settings for your MongoDB server, add the following lines to the minion config files. .. code-block:: yaml mongo.db: <database name> mongo.host: <server ip address> mongo.user: <MongoDB username> mongo.password: <MongoDB user password> mongo.port: 27017 Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location. .. code-block:: yaml alternative.mongo.db: <database name> alternative.mongo.host: <server ip address> alternative.mongo.user: <MongoDB username> alternative.mongo.password: <MongoDB user password> alternative.mongo.port: 27017 To use the mongo returner, append '--return mongo' to the salt command. .. code-block:: bash salt '*' test.ping --return mongo_return To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return mongo_return --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # import Salt libs import salt.utils.jid import salt.returners from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion # Import third party libs try: import pymongo PYMONGO_VERSION = _LooseVersion(pymongo.version) HAS_PYMONGO = True except ImportError: HAS_PYMONGO = False log = logging.getLogger(__name__) # Define the module's virtual name # currently only used iby _get_options __virtualname__ = 'mongo' def __virtual__(): if not HAS_PYMONGO: return False, 'Could not import mongo returner; pymongo is not installed.' return 'mongo_return' 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 _get_options(ret): ''' Get the monogo_return options from salt. ''' attrs = {'host': 'host', 'port': 'port', 'db': 'db', 'user': 'user', 'password': 'password', 'indexes': 'indexes'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) return _options 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 returner(ret): ''' Return data to a mongodb server ''' conn, mdb = _get_conn(ret) col = mdb[ret['id']] if isinstance(ret['return'], dict): back = _remove_dots(ret['return']) else: back = ret['return'] if isinstance(ret, dict): full_ret = _remove_dots(ret) else: full_ret = ret log.debug(back) sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret} if 'out' in ret: sdata['out'] = ret['out'] # save returns in the saltReturns collection in the json format: # { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>, # 'fun': <function>, 'full_ret': <unformatted return with dots removed>} # again we run into the issue with deprecated code from previous versions if PYMONGO_VERSION > _LooseVersion('2.3'): #using .copy() to ensure original data for load is unchanged mdb.saltReturns.insert_one(sdata.copy()) else: mdb.saltReturns.insert(sdata.copy()) 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 prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass
saltstack/salt
salt/returners/mongo_return.py
get_fun
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
Return the most recent jobs that have executed the named function
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_return.py#L218-L227
[ "def _get_conn(ret):\n '''\n Return a mongodb connection object\n '''\n _options = _get_options(ret)\n\n host = _options.get('host')\n port = _options.get('port')\n db_ = _options.get('db')\n user = _options.get('user')\n password = _options.get('password')\n indexes = _options.get('indexes', False)\n\n # at some point we should remove support for\n # pymongo versions < 2.3 until then there are\n # a bunch of these sections that need to be supported\n\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n conn = pymongo.MongoClient(host, port)\n else:\n conn = pymongo.Connection(host, port)\n mdb = conn[db_]\n\n if user and password:\n mdb.authenticate(user, password)\n\n if indexes:\n if PYMONGO_VERSION > _LooseVersion('2.3'):\n mdb.saltReturns.create_index('minion')\n mdb.saltReturns.create_index('jid')\n\n mdb.jobs.create_index('jid')\n else:\n mdb.saltReturns.ensure_index('minion')\n mdb.saltReturns.ensure_index('jid')\n\n mdb.jobs.ensure_index('jid')\n\n return conn, mdb\n" ]
# -*- coding: utf-8 -*- ''' Return data to a mongodb server Required python modules: pymongo This returner will send data from the minions to a MongoDB server. To configure the settings for your MongoDB server, add the following lines to the minion config files. .. code-block:: yaml mongo.db: <database name> mongo.host: <server ip address> mongo.user: <MongoDB username> mongo.password: <MongoDB user password> mongo.port: 27017 Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location. .. code-block:: yaml alternative.mongo.db: <database name> alternative.mongo.host: <server ip address> alternative.mongo.user: <MongoDB username> alternative.mongo.password: <MongoDB user password> alternative.mongo.port: 27017 To use the mongo returner, append '--return mongo' to the salt command. .. code-block:: bash salt '*' test.ping --return mongo_return To use the alternative configuration, append '--return_config alternative' to the salt command. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' test.ping --return mongo_return --return_config alternative To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command. .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' test.ping --return mongo --return_kwargs '{"db": "another-salt"}' ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # import Salt libs import salt.utils.jid import salt.returners from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion # Import third party libs try: import pymongo PYMONGO_VERSION = _LooseVersion(pymongo.version) HAS_PYMONGO = True except ImportError: HAS_PYMONGO = False log = logging.getLogger(__name__) # Define the module's virtual name # currently only used iby _get_options __virtualname__ = 'mongo' def __virtual__(): if not HAS_PYMONGO: return False, 'Could not import mongo returner; pymongo is not installed.' return 'mongo_return' 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 _get_options(ret): ''' Get the monogo_return options from salt. ''' attrs = {'host': 'host', 'port': 'port', 'db': 'db', 'user': 'user', 'password': 'password', 'indexes': 'indexes'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) return _options 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 returner(ret): ''' Return data to a mongodb server ''' conn, mdb = _get_conn(ret) col = mdb[ret['id']] if isinstance(ret['return'], dict): back = _remove_dots(ret['return']) else: back = ret['return'] if isinstance(ret, dict): full_ret = _remove_dots(ret) else: full_ret = ret log.debug(back) sdata = {'minion': ret['id'], 'jid': ret['jid'], 'return': back, 'fun': ret['fun'], 'full_ret': full_ret} if 'out' in ret: sdata['out'] = ret['out'] # save returns in the saltReturns collection in the json format: # { 'minion': <minion_name>, 'jid': <job_id>, 'return': <return info with dots removed>, # 'fun': <function>, 'full_ret': <unformatted return with dots removed>} # again we run into the issue with deprecated code from previous versions if PYMONGO_VERSION > _LooseVersion('2.3'): #using .copy() to ensure original data for load is unchanged mdb.saltReturns.insert_one(sdata.copy()) else: mdb.saltReturns.insert(sdata.copy()) 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 prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Included for API consistency ''' pass
saltstack/salt
salt/modules/acme.py
_cert_file
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))
Return expected path of a Let's Encrypt live cert
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L64-L68
null
# -*- coding: utf-8 -*- ''' ACME / Let's Encrypt module =========================== .. versionadded: 2016.3 This module currently looks for certbot script in the $PATH as - certbot, - lestsencrypt, - certbot-auto, - letsencrypt-auto eventually falls back to /opt/letsencrypt/letsencrypt-auto .. note:: Installation & configuration of the Let's Encrypt client can for example be done using https://github.com/saltstack-formulas/letsencrypt-formula .. warning:: Be sure to set at least accept-tos = True in cli.ini! Most parameters will fall back to cli.ini defaults if None is given. DNS plugins ----------- This module currently supports the CloudFlare certbot DNS plugin. The DNS plugin credentials file needs to be passed in using the ``dns_plugin_credentials`` argument. Make sure the appropriate certbot plugin for the wanted DNS provider is installed before using this module. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import datetime import os # Import salt libs import salt.utils.path log = logging.getLogger(__name__) LEA = salt.utils.path.which_bin(['certbot', 'letsencrypt', 'certbot-auto', 'letsencrypt-auto', '/opt/letsencrypt/letsencrypt-auto']) LE_LIVE = '/etc/letsencrypt/live/' if salt.utils.platform.is_freebsd(): LE_LIVE = '/usr/local' + LE_LIVE def __virtual__(): ''' Only work when letsencrypt-auto is installed ''' return LEA is not None, 'The ACME execution module cannot be loaded: letsencrypt-auto not installed.' 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 _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 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 certs(): ''' Return a list of active certificates CLI example: .. code-block:: bash salt 'vhost.example.com' acme.certs ''' return __salt__['file.readdir'](LE_LIVE)[2:] 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 expires(name): ''' The expiry date of a certificate in ISO format :param name: CommonName of cert CLI example: .. code-block:: bash salt 'gitlab.example.com' acme.expires dev.example.com ''' return _expires(name).isoformat() def has(name): ''' Test if a certificate is in the Let's Encrypt Live directory :param name: CommonName of cert Code example: .. code-block:: python if __salt__['acme.has']('dev.example.com'): log.info('That is one nice certificate you have there!') ''' return __salt__['file.file_exists'](_cert_file(name, 'cert')) def renew_by(name, window=None): ''' Date in ISO format when a certificate should first be renewed :param name: CommonName of cert :param window: number of days before expiry when renewal should take place ''' return _renew_by(name, window).isoformat() 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()
saltstack/salt
salt/modules/acme.py
_expires
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)
Return the expiry date of a cert :return datetime object of expiry date
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L71-L89
[ "def _cert_file(name, cert_type):\n '''\n Return expected path of a Let's Encrypt live cert\n '''\n return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type))\n" ]
# -*- coding: utf-8 -*- ''' ACME / Let's Encrypt module =========================== .. versionadded: 2016.3 This module currently looks for certbot script in the $PATH as - certbot, - lestsencrypt, - certbot-auto, - letsencrypt-auto eventually falls back to /opt/letsencrypt/letsencrypt-auto .. note:: Installation & configuration of the Let's Encrypt client can for example be done using https://github.com/saltstack-formulas/letsencrypt-formula .. warning:: Be sure to set at least accept-tos = True in cli.ini! Most parameters will fall back to cli.ini defaults if None is given. DNS plugins ----------- This module currently supports the CloudFlare certbot DNS plugin. The DNS plugin credentials file needs to be passed in using the ``dns_plugin_credentials`` argument. Make sure the appropriate certbot plugin for the wanted DNS provider is installed before using this module. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import datetime import os # Import salt libs import salt.utils.path log = logging.getLogger(__name__) LEA = salt.utils.path.which_bin(['certbot', 'letsencrypt', 'certbot-auto', 'letsencrypt-auto', '/opt/letsencrypt/letsencrypt-auto']) LE_LIVE = '/etc/letsencrypt/live/' if salt.utils.platform.is_freebsd(): LE_LIVE = '/usr/local' + LE_LIVE def __virtual__(): ''' Only work when letsencrypt-auto is installed ''' return LEA is not None, 'The ACME execution module cannot be loaded: letsencrypt-auto not installed.' 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 _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 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 certs(): ''' Return a list of active certificates CLI example: .. code-block:: bash salt 'vhost.example.com' acme.certs ''' return __salt__['file.readdir'](LE_LIVE)[2:] 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 expires(name): ''' The expiry date of a certificate in ISO format :param name: CommonName of cert CLI example: .. code-block:: bash salt 'gitlab.example.com' acme.expires dev.example.com ''' return _expires(name).isoformat() def has(name): ''' Test if a certificate is in the Let's Encrypt Live directory :param name: CommonName of cert Code example: .. code-block:: python if __salt__['acme.has']('dev.example.com'): log.info('That is one nice certificate you have there!') ''' return __salt__['file.file_exists'](_cert_file(name, 'cert')) def renew_by(name, window=None): ''' Date in ISO format when a certificate should first be renewed :param name: CommonName of cert :param window: number of days before expiry when renewal should take place ''' return _renew_by(name, window).isoformat() 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()
saltstack/salt
salt/modules/acme.py
_renew_by
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L92-L104
[ "def _expires(name):\n '''\n Return the expiry date of a cert\n\n :return datetime object of expiry date\n '''\n cert_file = _cert_file(name, 'cert')\n # Use the salt module if available\n if 'tls.cert_info' in __salt__:\n expiry = __salt__['tls.cert_info'](cert_file)['not_after']\n # Cobble it together using the openssl binary\n else:\n openssl_cmd = 'openssl x509 -in {0} -noout -enddate'.format(cert_file)\n # No %e format on my Linux'es here\n strptime_sux_cmd = 'date --date=\"$({0} | cut -d= -f2)\" +%s'.format(openssl_cmd)\n expiry = float(__salt__['cmd.shell'](strptime_sux_cmd, output_loglevel='quiet'))\n # expiry = datetime.datetime.strptime(expiry.split('=', 1)[-1], '%b %e %H:%M:%S %Y %Z')\n\n return datetime.datetime.fromtimestamp(expiry)\n" ]
# -*- coding: utf-8 -*- ''' ACME / Let's Encrypt module =========================== .. versionadded: 2016.3 This module currently looks for certbot script in the $PATH as - certbot, - lestsencrypt, - certbot-auto, - letsencrypt-auto eventually falls back to /opt/letsencrypt/letsencrypt-auto .. note:: Installation & configuration of the Let's Encrypt client can for example be done using https://github.com/saltstack-formulas/letsencrypt-formula .. warning:: Be sure to set at least accept-tos = True in cli.ini! Most parameters will fall back to cli.ini defaults if None is given. DNS plugins ----------- This module currently supports the CloudFlare certbot DNS plugin. The DNS plugin credentials file needs to be passed in using the ``dns_plugin_credentials`` argument. Make sure the appropriate certbot plugin for the wanted DNS provider is installed before using this module. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import datetime import os # Import salt libs import salt.utils.path log = logging.getLogger(__name__) LEA = salt.utils.path.which_bin(['certbot', 'letsencrypt', 'certbot-auto', 'letsencrypt-auto', '/opt/letsencrypt/letsencrypt-auto']) LE_LIVE = '/etc/letsencrypt/live/' if salt.utils.platform.is_freebsd(): LE_LIVE = '/usr/local' + LE_LIVE def __virtual__(): ''' Only work when letsencrypt-auto is installed ''' return LEA is not None, 'The ACME execution module cannot be loaded: letsencrypt-auto not installed.' 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 _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 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 certs(): ''' Return a list of active certificates CLI example: .. code-block:: bash salt 'vhost.example.com' acme.certs ''' return __salt__['file.readdir'](LE_LIVE)[2:] 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 expires(name): ''' The expiry date of a certificate in ISO format :param name: CommonName of cert CLI example: .. code-block:: bash salt 'gitlab.example.com' acme.expires dev.example.com ''' return _expires(name).isoformat() def has(name): ''' Test if a certificate is in the Let's Encrypt Live directory :param name: CommonName of cert Code example: .. code-block:: python if __salt__['acme.has']('dev.example.com'): log.info('That is one nice certificate you have there!') ''' return __salt__['file.file_exists'](_cert_file(name, 'cert')) def renew_by(name, window=None): ''' Date in ISO format when a certificate should first be renewed :param name: CommonName of cert :param window: number of days before expiry when renewal should take place ''' return _renew_by(name, window).isoformat() 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()
saltstack/salt
salt/modules/acme.py
cert
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L107-L258
[ "def _cert_file(name, cert_type):\n '''\n Return expected path of a Let's Encrypt live cert\n '''\n return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type))\n", "def needs_renewal(name, window=None):\n '''\n Check if a certificate needs renewal\n\n :param name: CommonName of cert\n :param window: Window in days to renew earlier or True/force to just return True\n\n Code example:\n\n .. code-block:: python\n\n if __salt__['acme.needs_renewal']('dev.example.com'):\n __salt__['acme.cert']('dev.example.com', **kwargs)\n else:\n log.info('Your certificate is still good')\n '''\n if window is not None and window in ('force', 'Force', True):\n return True\n\n return _renew_by(name, window) <= datetime.datetime.today()\n", "def expires(name):\n '''\n The expiry date of a certificate in ISO format\n\n :param name: CommonName of cert\n\n CLI example:\n\n .. code-block:: bash\n\n salt 'gitlab.example.com' acme.expires dev.example.com\n '''\n return _expires(name).isoformat()\n" ]
# -*- coding: utf-8 -*- ''' ACME / Let's Encrypt module =========================== .. versionadded: 2016.3 This module currently looks for certbot script in the $PATH as - certbot, - lestsencrypt, - certbot-auto, - letsencrypt-auto eventually falls back to /opt/letsencrypt/letsencrypt-auto .. note:: Installation & configuration of the Let's Encrypt client can for example be done using https://github.com/saltstack-formulas/letsencrypt-formula .. warning:: Be sure to set at least accept-tos = True in cli.ini! Most parameters will fall back to cli.ini defaults if None is given. DNS plugins ----------- This module currently supports the CloudFlare certbot DNS plugin. The DNS plugin credentials file needs to be passed in using the ``dns_plugin_credentials`` argument. Make sure the appropriate certbot plugin for the wanted DNS provider is installed before using this module. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import datetime import os # Import salt libs import salt.utils.path log = logging.getLogger(__name__) LEA = salt.utils.path.which_bin(['certbot', 'letsencrypt', 'certbot-auto', 'letsencrypt-auto', '/opt/letsencrypt/letsencrypt-auto']) LE_LIVE = '/etc/letsencrypt/live/' if salt.utils.platform.is_freebsd(): LE_LIVE = '/usr/local' + LE_LIVE def __virtual__(): ''' Only work when letsencrypt-auto is installed ''' return LEA is not None, 'The ACME execution module cannot be loaded: letsencrypt-auto not installed.' 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 _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 _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 certs(): ''' Return a list of active certificates CLI example: .. code-block:: bash salt 'vhost.example.com' acme.certs ''' return __salt__['file.readdir'](LE_LIVE)[2:] 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 expires(name): ''' The expiry date of a certificate in ISO format :param name: CommonName of cert CLI example: .. code-block:: bash salt 'gitlab.example.com' acme.expires dev.example.com ''' return _expires(name).isoformat() def has(name): ''' Test if a certificate is in the Let's Encrypt Live directory :param name: CommonName of cert Code example: .. code-block:: python if __salt__['acme.has']('dev.example.com'): log.info('That is one nice certificate you have there!') ''' return __salt__['file.file_exists'](_cert_file(name, 'cert')) def renew_by(name, window=None): ''' Date in ISO format when a certificate should first be renewed :param name: CommonName of cert :param window: number of days before expiry when renewal should take place ''' return _renew_by(name, window).isoformat() 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()
saltstack/salt
salt/modules/acme.py
info
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')
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L274-L300
[ "def _cert_file(name, cert_type):\n '''\n Return expected path of a Let's Encrypt live cert\n '''\n return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type))\n" ]
# -*- coding: utf-8 -*- ''' ACME / Let's Encrypt module =========================== .. versionadded: 2016.3 This module currently looks for certbot script in the $PATH as - certbot, - lestsencrypt, - certbot-auto, - letsencrypt-auto eventually falls back to /opt/letsencrypt/letsencrypt-auto .. note:: Installation & configuration of the Let's Encrypt client can for example be done using https://github.com/saltstack-formulas/letsencrypt-formula .. warning:: Be sure to set at least accept-tos = True in cli.ini! Most parameters will fall back to cli.ini defaults if None is given. DNS plugins ----------- This module currently supports the CloudFlare certbot DNS plugin. The DNS plugin credentials file needs to be passed in using the ``dns_plugin_credentials`` argument. Make sure the appropriate certbot plugin for the wanted DNS provider is installed before using this module. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import datetime import os # Import salt libs import salt.utils.path log = logging.getLogger(__name__) LEA = salt.utils.path.which_bin(['certbot', 'letsencrypt', 'certbot-auto', 'letsencrypt-auto', '/opt/letsencrypt/letsencrypt-auto']) LE_LIVE = '/etc/letsencrypt/live/' if salt.utils.platform.is_freebsd(): LE_LIVE = '/usr/local' + LE_LIVE def __virtual__(): ''' Only work when letsencrypt-auto is installed ''' return LEA is not None, 'The ACME execution module cannot be loaded: letsencrypt-auto not installed.' 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 _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 _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 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 certs(): ''' Return a list of active certificates CLI example: .. code-block:: bash salt 'vhost.example.com' acme.certs ''' return __salt__['file.readdir'](LE_LIVE)[2:] def expires(name): ''' The expiry date of a certificate in ISO format :param name: CommonName of cert CLI example: .. code-block:: bash salt 'gitlab.example.com' acme.expires dev.example.com ''' return _expires(name).isoformat() def has(name): ''' Test if a certificate is in the Let's Encrypt Live directory :param name: CommonName of cert Code example: .. code-block:: python if __salt__['acme.has']('dev.example.com'): log.info('That is one nice certificate you have there!') ''' return __salt__['file.file_exists'](_cert_file(name, 'cert')) def renew_by(name, window=None): ''' Date in ISO format when a certificate should first be renewed :param name: CommonName of cert :param window: number of days before expiry when renewal should take place ''' return _renew_by(name, window).isoformat() 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()
saltstack/salt
salt/modules/acme.py
needs_renewal
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()
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')
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L344-L363
[ "def _renew_by(name, window=None):\n '''\n Date before a certificate should be renewed\n\n :param name: Common Name of the certificate (DNS name of certificate)\n :param window: days before expiry date to renew\n :return datetime object of first renewal date\n '''\n expiry = _expires(name)\n if window is not None:\n expiry = expiry - datetime.timedelta(days=window)\n\n return expiry\n" ]
# -*- coding: utf-8 -*- ''' ACME / Let's Encrypt module =========================== .. versionadded: 2016.3 This module currently looks for certbot script in the $PATH as - certbot, - lestsencrypt, - certbot-auto, - letsencrypt-auto eventually falls back to /opt/letsencrypt/letsencrypt-auto .. note:: Installation & configuration of the Let's Encrypt client can for example be done using https://github.com/saltstack-formulas/letsencrypt-formula .. warning:: Be sure to set at least accept-tos = True in cli.ini! Most parameters will fall back to cli.ini defaults if None is given. DNS plugins ----------- This module currently supports the CloudFlare certbot DNS plugin. The DNS plugin credentials file needs to be passed in using the ``dns_plugin_credentials`` argument. Make sure the appropriate certbot plugin for the wanted DNS provider is installed before using this module. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import datetime import os # Import salt libs import salt.utils.path log = logging.getLogger(__name__) LEA = salt.utils.path.which_bin(['certbot', 'letsencrypt', 'certbot-auto', 'letsencrypt-auto', '/opt/letsencrypt/letsencrypt-auto']) LE_LIVE = '/etc/letsencrypt/live/' if salt.utils.platform.is_freebsd(): LE_LIVE = '/usr/local' + LE_LIVE def __virtual__(): ''' Only work when letsencrypt-auto is installed ''' return LEA is not None, 'The ACME execution module cannot be loaded: letsencrypt-auto not installed.' 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 _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 _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 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 certs(): ''' Return a list of active certificates CLI example: .. code-block:: bash salt 'vhost.example.com' acme.certs ''' return __salt__['file.readdir'](LE_LIVE)[2:] 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 expires(name): ''' The expiry date of a certificate in ISO format :param name: CommonName of cert CLI example: .. code-block:: bash salt 'gitlab.example.com' acme.expires dev.example.com ''' return _expires(name).isoformat() def has(name): ''' Test if a certificate is in the Let's Encrypt Live directory :param name: CommonName of cert Code example: .. code-block:: python if __salt__['acme.has']('dev.example.com'): log.info('That is one nice certificate you have there!') ''' return __salt__['file.file_exists'](_cert_file(name, 'cert')) def renew_by(name, window=None): ''' Date in ISO format when a certificate should first be renewed :param name: CommonName of cert :param window: number of days before expiry when renewal should take place ''' return _renew_by(name, window).isoformat()
saltstack/salt
salt/modules/drbd.py
_analyse_overview_field
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, ""
Split the field in drbd-overview
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L13-L24
null
# -*- coding: utf-8 -*- ''' DRBD administration module ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six log = logging.getLogger(__name__) 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 _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 _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_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_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 _empty(dummy): ''' Action of empty line of ``drbdadm status`` ''' pass def _unknown_parser(line): ''' Action of unsupported line of ``drbdadm status`` ''' global ret ret = {"Unknown parser": line} 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 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 # Global para for func status ret = [] resource = {} lastpnodevolumes = None 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
saltstack/salt
salt/modules/drbd.py
_count_spaces_startswith
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
Count the number of spaces before the first character
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L27-L39
null
# -*- coding: utf-8 -*- ''' DRBD administration module ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six log = logging.getLogger(__name__) 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_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 _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_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_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 _empty(dummy): ''' Action of empty line of ``drbdadm status`` ''' pass def _unknown_parser(line): ''' Action of unsupported line of ``drbdadm status`` ''' global ret ret = {"Unknown parser": line} 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 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 # Global para for func status ret = [] resource = {} lastpnodevolumes = None 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
saltstack/salt
salt/modules/drbd.py
_analyse_status_type
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'
Figure out the sections in drbdadm status
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L42-L67
null
# -*- coding: utf-8 -*- ''' DRBD administration module ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six log = logging.getLogger(__name__) 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 _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 _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_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_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 _empty(dummy): ''' Action of empty line of ``drbdadm status`` ''' pass def _unknown_parser(line): ''' Action of unsupported line of ``drbdadm status`` ''' global ret ret = {"Unknown parser": line} 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 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 # Global para for func status ret = [] resource = {} lastpnodevolumes = None 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
saltstack/salt
salt/modules/drbd.py
_add_res
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"] = []
Analyse the line of local resource of ``drbdadm status``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L70-L84
null
# -*- coding: utf-8 -*- ''' DRBD administration module ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six log = logging.getLogger(__name__) 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 _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 _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 _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_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 _empty(dummy): ''' Action of empty line of ``drbdadm status`` ''' pass def _unknown_parser(line): ''' Action of unsupported line of ``drbdadm status`` ''' global ret ret = {"Unknown parser": line} 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 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 # Global para for func status ret = [] resource = {} lastpnodevolumes = None 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
saltstack/salt
salt/modules/drbd.py
_add_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)
Analyse the line of volumes of ``drbdadm status``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L87-L102
null
# -*- coding: utf-8 -*- ''' DRBD administration module ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six log = logging.getLogger(__name__) 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 _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 _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 _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_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 _empty(dummy): ''' Action of empty line of ``drbdadm status`` ''' pass def _unknown_parser(line): ''' Action of unsupported line of ``drbdadm status`` ''' global ret ret = {"Unknown parser": line} 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 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 # Global para for func status ret = [] resource = {} lastpnodevolumes = None 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
saltstack/salt
salt/modules/drbd.py
_add_peernode
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"]
Analyse the line of peer nodes of ``drbdadm status``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L105-L119
null
# -*- coding: utf-8 -*- ''' DRBD administration module ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six log = logging.getLogger(__name__) 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 _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 _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 _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_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 _empty(dummy): ''' Action of empty line of ``drbdadm status`` ''' pass def _unknown_parser(line): ''' Action of unsupported line of ``drbdadm status`` ''' global ret ret = {"Unknown parser": line} 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 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 # Global para for func status ret = [] resource = {} lastpnodevolumes = None 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
saltstack/salt
salt/modules/drbd.py
_line_parser
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)
Call action for different lines
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L137-L154
[ "def _analyse_status_type(line):\n '''\n Figure out the sections in drbdadm status\n '''\n spaces = _count_spaces_startswith(line)\n\n if spaces is None:\n return ''\n\n switch = {\n 0: 'RESOURCE',\n 2: {' disk:': 'LOCALDISK', ' role:': 'PEERNODE', ' connection:': 'PEERNODE'},\n 4: {' peer-disk:': 'PEERDISK'}\n }\n\n ret = switch.get(spaces, 'UNKNOWN')\n\n # isinstance(ret, str) only works when run directly, calling need unicode(six)\n if isinstance(ret, six.text_type):\n return ret\n\n for x in ret:\n if x in line:\n return ret[x]\n\n return 'UNKNOWN'\n" ]
# -*- coding: utf-8 -*- ''' DRBD administration module ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six log = logging.getLogger(__name__) 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 _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 _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 _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_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_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 _empty(dummy): ''' Action of empty line of ``drbdadm status`` ''' pass def _unknown_parser(line): ''' Action of unsupported line of ``drbdadm status`` ''' global ret ret = {"Unknown parser": line} 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 # Global para for func status ret = [] resource = {} lastpnodevolumes = None 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
saltstack/salt
salt/modules/drbd.py
overview
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L157-L228
[ "def _analyse_overview_field(content):\n '''\n Split the field in drbd-overview\n '''\n if \"(\" in content:\n # Output like \"Connected(2*)\" or \"UpToDate(2*)\"\n return content.split(\"(\")[0], content.split(\"(\")[0]\n elif \"/\" in content:\n # Output like \"Primar/Second\" or \"UpToDa/UpToDa\"\n return content.split(\"/\")[0], content.split(\"/\")[1]\n\n return content, \"\"\n" ]
# -*- coding: utf-8 -*- ''' DRBD administration module ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six log = logging.getLogger(__name__) 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 _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 _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 _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_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_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 _empty(dummy): ''' Action of empty line of ``drbdadm status`` ''' pass def _unknown_parser(line): ''' Action of unsupported line of ``drbdadm status`` ''' global ret ret = {"Unknown parser": line} 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) # Global para for func status ret = [] resource = {} lastpnodevolumes = None 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
saltstack/salt
salt/modules/drbd.py
status
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
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>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L237-L283
[ "def _line_parser(line):\n '''\n Call action for different lines\n '''\n section = _analyse_status_type(line)\n fields = line.strip().split()\n\n switch = {\n '': _empty,\n 'RESOURCE': _add_res,\n 'PEERNODE': _add_peernode,\n 'LOCALDISK': _add_volume,\n 'PEERDISK': _add_volume,\n }\n\n func = switch.get(section, _unknown_parser)\n\n func(line)\n" ]
# -*- coding: utf-8 -*- ''' DRBD administration module ''' from __future__ import absolute_import, print_function, unicode_literals import logging from salt.ext import six log = logging.getLogger(__name__) 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 _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 _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 _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_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_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 _empty(dummy): ''' Action of empty line of ``drbdadm status`` ''' pass def _unknown_parser(line): ''' Action of unsupported line of ``drbdadm status`` ''' global ret ret = {"Unknown parser": line} 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 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 # Global para for func status ret = [] resource = {} lastpnodevolumes = None
saltstack/salt
salt/modules/rdp.py
_parse_return_code_powershell
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))
return from the input string the return code of the powershell command
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L34-L43
null
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import re # Import Salt libs import salt.utils.platform from salt.utils.decorators import depends try: from pywintypes import error as PyWinError import win32ts _HAS_WIN32TS_DEPENDENCIES = True except ImportError: _HAS_WIN32TS_DEPENDENCIES = False _LOG = logging.getLogger(__name__) def __virtual__(): ''' Only works on Windows systems ''' if salt.utils.platform.is_windows(): return 'rdp' return (False, 'Module only works on Windows.') 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 enable(): ''' Enable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.enable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(1,1)')) == 0 def disable(): ''' Disable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.disable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(0,1)')) == 0 def status(): ''' Show if rdp is enabled on the server CLI Example: .. code-block:: bash salt '*' rdp.status ''' out = int(_psrdp('echo $RDP.AllowTSConnections').strip()) return out != 0 @depends(_HAS_WIN32TS_DEPENDENCIES) 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']) @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES) 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
saltstack/salt
salt/modules/rdp.py
_psrdp
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)
Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the command cmd returns the STDOUT of the command
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L46-L55
null
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import re # Import Salt libs import salt.utils.platform from salt.utils.decorators import depends try: from pywintypes import error as PyWinError import win32ts _HAS_WIN32TS_DEPENDENCIES = True except ImportError: _HAS_WIN32TS_DEPENDENCIES = False _LOG = logging.getLogger(__name__) def __virtual__(): ''' Only works on Windows systems ''' if salt.utils.platform.is_windows(): return 'rdp' return (False, 'Module only works on Windows.') 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 enable(): ''' Enable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.enable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(1,1)')) == 0 def disable(): ''' Disable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.disable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(0,1)')) == 0 def status(): ''' Show if rdp is enabled on the server CLI Example: .. code-block:: bash salt '*' rdp.status ''' out = int(_psrdp('echo $RDP.AllowTSConnections').strip()) return out != 0 @depends(_HAS_WIN32TS_DEPENDENCIES) 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']) @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES) 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
saltstack/salt
salt/modules/rdp.py
list_sessions
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'])
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L104-L151
null
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import re # Import Salt libs import salt.utils.platform from salt.utils.decorators import depends try: from pywintypes import error as PyWinError import win32ts _HAS_WIN32TS_DEPENDENCIES = True except ImportError: _HAS_WIN32TS_DEPENDENCIES = False _LOG = logging.getLogger(__name__) def __virtual__(): ''' Only works on Windows systems ''' if salt.utils.platform.is_windows(): return 'rdp' return (False, 'Module only works on Windows.') 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 _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 enable(): ''' Enable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.enable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(1,1)')) == 0 def disable(): ''' Disable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.disable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(0,1)')) == 0 def status(): ''' Show if rdp is enabled on the server CLI Example: .. code-block:: bash salt '*' rdp.status ''' out = int(_psrdp('echo $RDP.AllowTSConnections').strip()) return out != 0 @depends(_HAS_WIN32TS_DEPENDENCIES) @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES) 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
saltstack/salt
salt/modules/rdp.py
get_session
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L155-L181
null
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import re # Import Salt libs import salt.utils.platform from salt.utils.decorators import depends try: from pywintypes import error as PyWinError import win32ts _HAS_WIN32TS_DEPENDENCIES = True except ImportError: _HAS_WIN32TS_DEPENDENCIES = False _LOG = logging.getLogger(__name__) def __virtual__(): ''' Only works on Windows systems ''' if salt.utils.platform.is_windows(): return 'rdp' return (False, 'Module only works on Windows.') 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 _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 enable(): ''' Enable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.enable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(1,1)')) == 0 def disable(): ''' Disable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.disable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(0,1)')) == 0 def status(): ''' Show if rdp is enabled on the server CLI Example: .. code-block:: bash salt '*' rdp.status ''' out = int(_psrdp('echo $RDP.AllowTSConnections').strip()) return out != 0 @depends(_HAS_WIN32TS_DEPENDENCIES) 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']) @depends(_HAS_WIN32TS_DEPENDENCIES) @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES) 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
saltstack/salt
salt/modules/rdp.py
disconnect_session
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L185-L207
null
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import re # Import Salt libs import salt.utils.platform from salt.utils.decorators import depends try: from pywintypes import error as PyWinError import win32ts _HAS_WIN32TS_DEPENDENCIES = True except ImportError: _HAS_WIN32TS_DEPENDENCIES = False _LOG = logging.getLogger(__name__) def __virtual__(): ''' Only works on Windows systems ''' if salt.utils.platform.is_windows(): return 'rdp' return (False, 'Module only works on Windows.') 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 _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 enable(): ''' Enable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.enable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(1,1)')) == 0 def disable(): ''' Disable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.disable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(0,1)')) == 0 def status(): ''' Show if rdp is enabled on the server CLI Example: .. code-block:: bash salt '*' rdp.status ''' out = int(_psrdp('echo $RDP.AllowTSConnections').strip()) return out != 0 @depends(_HAS_WIN32TS_DEPENDENCIES) 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']) @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES) @depends(_HAS_WIN32TS_DEPENDENCIES) 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
saltstack/salt
salt/modules/rdp.py
logoff_session
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
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rdp.py#L211-L233
null
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import re # Import Salt libs import salt.utils.platform from salt.utils.decorators import depends try: from pywintypes import error as PyWinError import win32ts _HAS_WIN32TS_DEPENDENCIES = True except ImportError: _HAS_WIN32TS_DEPENDENCIES = False _LOG = logging.getLogger(__name__) def __virtual__(): ''' Only works on Windows systems ''' if salt.utils.platform.is_windows(): return 'rdp' return (False, 'Module only works on Windows.') 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 _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 enable(): ''' Enable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.enable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(1,1)')) == 0 def disable(): ''' Disable RDP the service on the server CLI Example: .. code-block:: bash salt '*' rdp.disable ''' return _parse_return_code_powershell( _psrdp('$RDP.SetAllowTsConnections(0,1)')) == 0 def status(): ''' Show if rdp is enabled on the server CLI Example: .. code-block:: bash salt '*' rdp.status ''' out = int(_psrdp('echo $RDP.AllowTSConnections').strip()) return out != 0 @depends(_HAS_WIN32TS_DEPENDENCIES) 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']) @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES) 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 @depends(_HAS_WIN32TS_DEPENDENCIES)
saltstack/salt
salt/runners/fileserver.py
envs
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))
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L11-L39
[ "def envs(self, back=None, sources=False):\n '''\n Return the environments for the named backend or all backends\n '''\n back = self.backends(back)\n ret = set()\n if sources:\n ret = {}\n for fsb in back:\n fstr = '{0}.envs'.format(fsb)\n kwargs = {'ignore_cache': True} \\\n if 'ignore_cache' in _argspec(self.servers[fstr]).args \\\n and self.opts['__role'] == 'minion' \\\n else {}\n if sources:\n ret[fsb] = self.servers[fstr](**kwargs)\n else:\n ret.update(self.servers[fstr](**kwargs))\n if sources:\n return ret\n return list(ret)\n" ]
# -*- coding: utf-8 -*- ''' Directly manage the Salt fileserver plugins ''' from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.fileserver 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 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 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 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 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 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 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_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 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
saltstack/salt
salt/runners/fileserver.py
clear_file_list_cache
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)
.. 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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L42-L147
[ "def clear_file_list_cache(self, load):\n '''\n Deletes the file_lists cache files\n '''\n if 'env' in load:\n # \"env\" is not supported; Use \"saltenv\".\n load.pop('env')\n\n saltenv = load.get('saltenv', [])\n if saltenv is not None:\n if not isinstance(saltenv, list):\n try:\n saltenv = [x.strip() for x in saltenv.split(',')]\n except AttributeError:\n saltenv = [x.strip() for x in six.text_type(saltenv).split(',')]\n\n for idx, val in enumerate(saltenv):\n if not isinstance(val, six.string_types):\n saltenv[idx] = six.text_type(val)\n\n ret = {}\n fsb = self.backends(load.pop('fsbackend', None))\n list_cachedir = os.path.join(self.opts['cachedir'], 'file_lists')\n try:\n file_list_backends = os.listdir(list_cachedir)\n except OSError as exc:\n if exc.errno == errno.ENOENT:\n log.debug('No file list caches found')\n return {}\n else:\n log.error(\n 'Failed to get list of saltenvs for which the master has '\n 'cached file lists: %s', exc\n )\n\n for back in file_list_backends:\n # Account for the fact that the file_list cache directory for gitfs\n # is 'git', hgfs is 'hg', etc.\n back_virtualname = re.sub('fs$', '', back)\n try:\n cache_files = os.listdir(os.path.join(list_cachedir, back))\n except OSError as exc:\n log.error(\n 'Failed to find file list caches for saltenv \\'%s\\': %s',\n back, exc\n )\n continue\n for cache_file in cache_files:\n try:\n cache_saltenv, extension = cache_file.rsplit('.', 1)\n except ValueError:\n # Filename has no dot in it. Not a cache file, ignore.\n continue\n if extension != 'p':\n # Filename does not end in \".p\". Not a cache file, ignore.\n continue\n elif back_virtualname not in fsb or \\\n (saltenv is not None and cache_saltenv not in saltenv):\n log.debug(\n 'Skipping %s file list cache for saltenv \\'%s\\'',\n back, cache_saltenv\n )\n continue\n try:\n os.remove(os.path.join(list_cachedir, back, cache_file))\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n log.error('Failed to remove %s: %s',\n exc.filename, exc.strerror)\n else:\n ret.setdefault(back, []).append(cache_saltenv)\n log.debug(\n 'Removed %s file list cache for saltenv \\'%s\\'',\n cache_saltenv, back\n )\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Directly manage the Salt fileserver plugins ''' from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.fileserver 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 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 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 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 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 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 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_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 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
saltstack/salt
salt/runners/fileserver.py
file_list
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)
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L150-L193
null
# -*- coding: utf-8 -*- ''' Directly manage the Salt fileserver plugins ''' from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.fileserver 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 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 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 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 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 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 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_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 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
saltstack/salt
salt/runners/fileserver.py
symlink_list
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)
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
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L196-L239
null
# -*- coding: utf-8 -*- ''' Directly manage the Salt fileserver plugins ''' from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.fileserver 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 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 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 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 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 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 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_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 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