Build a systemctl command line. Treat unit names without one
    of the valid suffixes as a service.
170861
def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,
                   root=None):
    '''
    
    '''
    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
266398
def _replace_service_arg(self, name, index, args):
        
        args[index] = self.get_instantiated_service(name)
1264536
def name(cls):
        """"""
        name = cls.__name__.replace("_", "-").lower()
        name = name[4:] if name.startswith("cmd-") else name
        return name
737848
def _systemctl_status(name):
    '''
    
    '''
    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]
1202239
def valid_command_names_from(*args)
      arg_string = args.delete_if { |value| value =~ /^-/ }.join ' '
      commands.keys.find_all { |name| name if /^#{name}\b/.match arg_string }
    end
544012
def enabled(name, root=None, **kwargs):  # pylint: disable=unused-argument
    '''
    
    '''
    # Try 'systemctl is-enabled' first, then look for a symlink created by
    # systemctl (older systemd releases did not support using is-enabled to
    # 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
1317449
def init_command_set(self, scrapyd_url):
        

        if scrapyd_url[-1:] != '/':
            scrapyd_url = scrapyd_url + '/'
        self['daemonstatus'] = [scrapyd_url + 'daemonstatus.json', http_utils.METHOD_GET]
        self['addversion'] = [scrapyd_url + 'addversion.json', http_utils.METHOD_POST]
        self['schedule'] = [scrapyd_url + 'schedule.json', http_utils.METHOD_POST]
        self['cancel'] = [scrapyd_url + 'cancel.json', http_utils.METHOD_POST]
        self['listprojects'] = [scrapyd_url + 'listprojects.json', http_utils.METHOD_GET]
        self['listversions'] = [scrapyd_url + 'listversions.json', http_utils.METHOD_GET]
        self['listspiders'] = [scrapyd_url + 'listspiders.json', http_utils.METHOD_GET]
        self['listjobs'] = [scrapyd_url + 'listjobs.json', http_utils.METHOD_GET]
        self['delversion'] = [scrapyd_url + 'delversion.json', http_utils.METHOD_POST]
        self['delproject'] = [scrapyd_url + 'delproject.json', http_utils.METHOD_POST]
        self['logs'] = [scrapyd_url + 'logs/', http_utils.METHOD_GET]
523419
def _ensure_systemd(version):
    '''
    
    '''
    try:
        version = int(version)
    except ValueError:
        raise CommandExecutionError('Invalid version \'{0}\''.format(version))

    try:
        installed = _sd_version()
        log.debug('nspawn: detected systemd %s', installed)
    except (IndexError, ValueError):
        raise CommandExecutionError('nspawn: Unable to get systemd version')

    if installed < version:
        raise CommandExecutionError(
            'This function requires systemd >= {0} '
            '(Detected version: {1}).'.format(version, installed)
        )
644090
def version(context=None):
    '''
    
    '''
    contextkey = 'salt.utils.systemd.version'
    if isinstance(context, dict):
        # Can't put this if block on the same line as the above if block,
        # because it will break the elif below.
        if contextkey in context:
            return context[contextkey]
    elif context is not None:
        raise SaltInvocationError('context must be a dictionary if passed')
    stdout = subprocess.Popen(
        ['systemctl', '--version'],
        close_fds=True,
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
    outstr = salt.utils.stringutils.to_str(stdout)
    try:
        ret = int(re.search(r'\w+ ([0-9]+)', outstr.splitlines()[0]).group(1))
    except (AttributeError, IndexError, ValueError):
        log.error(
            'Unable to determine systemd version from systemctl '
            '--version, output follows:\n%s', outstr
        )
        return None
    else:
        try:
            context[contextkey] = ret
        except TypeError:
            pass
        return ret
902805
def stop(self):
        
        try:
            sh.systemctl.stop(self.name)
        except sh.ErrorReturnCode_5:
            self.logger.debug('Service not running.')
1005089
def _sysv_services():
    '''
    
    '''
    _services = []
    output = __salt__['cmd.run'](['chkconfig', '--list'], python_shell=False)
    for line in output.splitlines():
        comps = line.split()
        try:
            if comps[1].startswith('0:'):
                _services.append(comps[0])
        except IndexError:
            continue
    # Return only the services that have an initscript present
    return [x for x in _services if _service_is_sysv(x)]
65730
def _service_is_sysv(name):
    '''
    
    '''
    script = '/etc/init.d/{0}'.format(name)
    return not _service_is_upstart(name) and os.access(script, os.X_OK)
833043
def build(
    c,
    clean=False,
    browse=False,
    nitpick=False,
    opts=None,
    source=None,
    target=None,
):
    
    if clean:
        _clean(c)
    if opts is None:
        opts = ""
    if nitpick:
        opts += " -n -W -T"
    cmd = "sphinx-build{0} {1} {2}".format(
        (" " + opts) if opts else "",
        source or c.sphinx.source,
        target or c.sphinx.target,
    )
    c.run(cmd, pty=True)
    if browse:
        _browse(c)
37958
def service(service_name, options={})
      options = {
          'print_command' => false,
          'failure_message' => "required service '#{service_name}' is not running."
      }.merge(string_keys(options))
      system_exit_on_error("ps ax | grep '#{service_name.gsub(/^(.)/, "[\\1]")}'", options)
    end
109133
async def DestroyUnits(self, unit_names):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='Application',
                   request='DestroyUnits',
                   version=3,
                   params=_params)
        _params['unit-names'] = unit_names
        reply = await self.rpc(msg)
        return reply
895738
def clean_build(self):
        
        import shutil

        if self.build_fs.exists:
            try:
                shutil.rmtree(self.build_fs.getsyspath('/'))
            except NoSysPathError:
                pass
752547
def build_sh_cmd(cmd, cwd=None):
    
    args = cmd.split()
    return getattr(sh, args[0]).bake(_cwd=cwd, *args[1:])