Ejemplo n.º 1
0
def pvcreate(devices, **kwargs):
    '''
    Set a physical device to be used as an LVM physical volume

    CLI Examples:

    .. code-block:: bash

        salt mymachine lvm.pvcreate /dev/sdb1,/dev/sdb2
        salt mymachine lvm.pvcreate /dev/sdb1 dataalignmentoffset=7s
    '''
    if not devices:
        return 'Error: at least one device is required'

    cmd = 'pvcreate'
    for device in devices.split(','):
        cmd += ' {0}'.format(device)
    valid = ('metadatasize', 'dataalignment', 'dataalignmentoffset',
             'pvmetadatacopies', 'metadatacopies', 'metadataignore',
             'restorefile', 'norestorefile', 'labelsector',
             'setphysicalvolumesize', 'force', 'uuid', 'zero', 'metadatatype')
    for var in kwargs['kwargs'].keys():
        if kwargs['kwargs'][var] and var in valid:
            cmd += ' --{0} {1}'.format(var, kwargs['kwargs'][var])
    result = __salt__['cmd.run_all'](cmd)
    state_std(kwargs, result)
    if result['retcode'] != 0 or result['stderr']:
        return result['stderr']
    out = result['stdout'].splitlines()
    return out[0]
Ejemplo n.º 2
0
def remount(name, device, mkmnt=False, fstype='', opts='defaults', **kwargs):
    '''
    Attempt to remount a device, if the device is not already mounted, mount
    is called

    CLI Example:

    .. code-block:: bash

        salt '*' mount.remount /mnt/foo /dev/sdz1 True
    '''
    if isinstance(opts, string_types):
        opts = opts.split(',')
    mnts = active()
    if name in mnts:
        # The mount point is mounted, attempt to remount it with the given data
        if 'remount' not in opts:
            opts.append('remount')
        lopts = ','.join(opts)
        args = '-o {0}'.format(lopts)
        if fstype:
            args += ' -t {0}'.format(fstype)
        cmd = 'mount {0} {1} {2} '.format(args, device, name)
        out = __salt__['cmd.run_stdall'](cmd)
        state_std(kwargs, out)
        if out['retcode']:
            return out['stderr']
        return True
    # Mount a filesystem that isn't already
    return mount(name, device, mkmnt, fstype, opts)
Ejemplo n.º 3
0
def vgcreate(vgname, devices, **kwargs):
    '''
    Create an LVM volume group

    CLI Examples:

    .. code-block:: bash

        salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
        salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y
    '''
    if not vgname or not devices:
        return 'Error: vgname and device(s) are both required'

    cmd = 'vgcreate {0}'.format(vgname)
    for device in devices.split(','):
        cmd += ' {0}'.format(device)
    valid = ('clustered', 'maxlogicalvolumes', 'maxphysicalvolumes',
             'vgmetadatacopies', 'metadatacopies', 'physicalextentsize',
             'metadatatype', 'autobackup', 'addtag', 'alloc')
    for var in kwargs['kwargs'].keys():
        if kwargs['kwargs'][var] and var in valid:
            cmd += ' --{0} {1}'.format(var, kwargs['kwargs'][var])
    result = __salt__['cmd.run_all'](cmd)
    state_std(kwargs, result)
    if result['retcode'] != 0 or result['stderr']:
        return result['stderr']
    out = result['stdout'].splitlines()
    vgdata = vgdisplay(vgname)
    vgdata['Output from vgcreate'] = out[0].strip()
    return vgdata
Ejemplo n.º 4
0
def _git_run(cmd, cwd=None, runas=None, identity=None, **kwargs):
    '''
    simple, throw an exception with the error message on an error return code.

    this function may be moved to the command module, spliced with
    'cmd.run_all', and used as an alternative to 'cmd.run_all'. Some
    commands don't return proper retcodes, so this can't replace 'cmd.run_all'.
    '''
    env = {}

    if identity:
        helper = _git_ssh_helper(identity)

        env = {'GIT_SSH': helper}

    result = __salt__['cmd.run_stdall'](cmd,
                                        cwd=cwd,
                                        runas=runas,
                                        env=env,
                                        **kwargs)
    state_std(kwargs, result)
    if identity:
        os.unlink(helper)

    retcode = result['retcode']

    if retcode == 0:
        return result['stdout']
    else:
        raise exceptions.CommandExecutionError(result['stderr'])
Ejemplo n.º 5
0
def swapon(name, priority=None, **kwargs):
    '''
    Activate a swap disk

    CLI Example:

    .. code-block:: bash

        salt '*' mount.swapon /root/swapfile
    '''
    ret = {}
    on_ = swaps()
    if name in on_:
        ret['stats'] = on_[name]
        ret['new'] = False
        return ret
    cmd = 'swapon {0}'.format(name)
    if priority:
        cmd += ' -p {0}'.format(priority)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    on_ = swaps()
    if name in on_:
        ret['stats'] = on_[name]
        ret['new'] = True
        return ret
    return ret
Ejemplo n.º 6
0
def restart(name='all', user=None, conf_file=None, bin_env=None, **kwargs):
    '''
    Restart the named service.
    Process group names should not include a trailing asterisk.

    user
        user to run supervisorctl as
    conf_file
        path to supervisorctl config file
    bin_env
        path to supervisorctl bin or path to virtualenv with supervisor
        installed

    CLI Example:

    .. code-block:: bash

        salt '*' supervisord.restart <service>
        salt '*' supervisord.restart <group>:
    '''
    ret = __salt__['cmd.run_stdall'](_ctl_cmd('restart', name, conf_file,
                                              bin_env),
                                     runas=user)
    state_std(kwargs, ret)
    return _get_return(ret)
Ejemplo n.º 7
0
def remove(name, user=None, conf_file=None, bin_env=None, **kwargs):
    '''
    Removes process/group from active config

    user
        user to run supervisorctl as
    conf_file
        path to supervisorctl config file
    bin_env
        path to supervisorctl bin or path to virtualenv with supervisor
        installed

    CLI Example:

    .. code-block:: bash

        salt '*' supervisord.remove <name>
    '''
    if name.endswith(':'):
        name = name[:-1]
    ret = __salt__['cmd.run_stdall'](_ctl_cmd('remove', name, conf_file,
                                              bin_env),
                                     runas=user)
    state_std(kwargs, ret)
    return _get_return(ret)
Ejemplo n.º 8
0
def pull(cwd, opts=None, user=None, **kwargs):
    '''
    Perform a pull on the given repository

    cwd
        The path to the Mercurial repository

    opts : None
        Any additional options to add to the command line

    user : None
        Run hg as a user other than what the minion runs as

    CLI Example:

    .. code-block:: bash

        salt '*' hg.pull /path/to/repo '-u'
    '''
    _check_hg()

    if not opts:
        opts = ''
    result = __salt__['cmd.run_stdall']('hg pull {0}'.format(opts), cwd=cwd, runas=user)
    state_std(kwargs, result)
    return result['stdout']
Ejemplo n.º 9
0
def update(cwd, rev, force=False, user=None, **kwargs):
    '''
    Update to a given revision

    cwd
        The path to the Mercurial repository

    rev
        The revision to update to

    force : False
        Force an update

    user : None
        Run hg as a user other than what the minion runs as

    CLI Example:

    .. code-block:: bash

        salt devserver1 hg.update /path/to/repo somebranch
    '''
    _check_hg()

    cmd = 'hg update {0}{1}'.format(rev, ' -C' if force else '')
    result = __salt__['cmd.run_stdall'](cmd, cwd=cwd, runas=user)
    state_std(kwargs, result)
    return result['stdout']
Ejemplo n.º 10
0
def clone(cwd, repository, opts=None, user=None, **kwargs):
    '''
    Clone a new repository

    cwd
        The path to the Mercurial repository

    repository
        The hg URI of the repository

    opts : None
        Any additional options to add to the command line

    user : None
        Run hg as a user other than what the minion runs as

    CLI Example:

    .. code-block:: bash

        salt '*' hg.clone /path/to/repo https://bitbucket.org/birkenfeld/sphinx
    '''
    _check_hg()

    if not opts:
        opts = ''
    cmd = 'hg clone {0} {1} {2}'.format(repository, cwd, opts)
    result = __salt__['cmd.run_stdall'](cmd, runas=user)
    state_std(kwargs, result)
    return result['stdout']
Ejemplo n.º 11
0
def restart(name='all', user=None, conf_file=None, bin_env=None, **kwargs):
    '''
    Restart the named service.
    Process group names should not include a trailing asterisk.

    user
        user to run supervisorctl as
    conf_file
        path to supervisorctl config file
    bin_env
        path to supervisorctl bin or path to virtualenv with supervisor
        installed

    CLI Example:

    .. code-block:: bash

        salt '*' supervisord.restart <service>
        salt '*' supervisord.restart <group>:
    '''
    ret = __salt__['cmd.run_stdall'](
        _ctl_cmd('restart', name, conf_file, bin_env), runas=user
    )
    state_std(kwargs, ret)
    return _get_return(ret)
Ejemplo n.º 12
0
def enable(name, **kwargs):
    '''
    Enable the named service to start at boot

    CLI Example:

    .. code-block:: bash

        salt '*' service.enable <service name>
    '''
    osmajor = _osrel()[0]
    if osmajor < '6':
        cmd = 'update-rc.d -f {0} defaults 99'.format(name)
    else:
        cmd = 'update-rc.d {0} enable'.format(name)
    try:
        if int(osmajor) >= 6:
            cmd = 'insserv {0} && '.format(name) + cmd
    except ValueError:
        if osmajor == 'testing/unstable' or osmajor == 'unstable':
            cmd = 'insserv {0} && '.format(name) + cmd

    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 13
0
def _git_run(cmd, cwd=None, runas=None, identity=None, **kwargs):
    '''
    simple, throw an exception with the error message on an error return code.

    this function may be moved to the command module, spliced with
    'cmd.run_all', and used as an alternative to 'cmd.run_all'. Some
    commands don't return proper retcodes, so this can't replace 'cmd.run_all'.
    '''
    env = {}

    if identity:
        helper = _git_ssh_helper(identity)

        env = {
            'GIT_SSH': helper
        }

    result = __salt__['cmd.run_stdall'](cmd,
                                     cwd=cwd,
                                     runas=runas,
                                     env=env,
                                     **kwargs)
    state_std(kwargs, result)
    if identity:
        os.unlink(helper)

    retcode = result['retcode']
  
    if retcode == 0:
        return result['stdout']
    else:
        raise exceptions.CommandExecutionError(result['stderr'])
Ejemplo n.º 14
0
def revision(cwd, rev='tip', short=False, user=None, **kwargs):
    '''
    Returns the long hash of a given identifier (hash, branch, tag, HEAD, etc)

    cwd
        The path to the Mercurial repository

    rev: tip
        The revision

    short: False
        Return an abbreviated commit hash

    user : None
        Run hg as a user other than what the minion runs as

    CLI Example:

    .. code-block:: bash

        salt '*' hg.revision /path/to/repo mybranch
    '''
    _check_hg()

    cmd = 'hg id -i{short} {rev}'.format(
        short=' --debug' if not short else '',
        rev=' -r {0}'.format(rev))

    result = __salt__['cmd.run_stdall'](cmd, cwd=cwd, runas=user)
    state_std(kwargs, result)
    
    if result['retcode'] == 0:
        return result['stdout']
    else:
        return '', result
Ejemplo n.º 15
0
def pvcreate(devices, **kwargs):
    '''
    Set a physical device to be used as an LVM physical volume

    CLI Examples:

    .. code-block:: bash

        salt mymachine lvm.pvcreate /dev/sdb1,/dev/sdb2
        salt mymachine lvm.pvcreate /dev/sdb1 dataalignmentoffset=7s
    '''
    if not devices:
        return 'Error: at least one device is required'

    cmd = 'pvcreate'
    for device in devices.split(','):
        cmd += ' {0}'.format(device)
    valid = ('metadatasize', 'dataalignment', 'dataalignmentoffset',
             'pvmetadatacopies', 'metadatacopies', 'metadataignore',
             'restorefile', 'norestorefile', 'labelsector',
             'setphysicalvolumesize', 'force', 'uuid', 'zero', 'metadatatype')
    for var in kwargs['kwargs'].keys():
        if kwargs['kwargs'][var] and var in valid:
            cmd += ' --{0} {1}'.format(var, kwargs['kwargs'][var])
    result = __salt__['cmd.run_all'](cmd)
    state_std(kwargs, result)
    if result['retcode'] != 0 or result['stderr']:
        return result['stderr']
    out = result['stdout'].splitlines()
    return out[0]
Ejemplo n.º 16
0
def vgcreate(vgname, devices, **kwargs):
    '''
    Create an LVM volume group

    CLI Examples:

    .. code-block:: bash

        salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
        salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y
    '''
    if not vgname or not devices:
        return 'Error: vgname and device(s) are both required'

    cmd = 'vgcreate {0}'.format(vgname)
    for device in devices.split(','):
        cmd += ' {0}'.format(device)
    valid = ('clustered', 'maxlogicalvolumes', 'maxphysicalvolumes',
             'vgmetadatacopies', 'metadatacopies', 'physicalextentsize',
             'metadatatype', 'autobackup', 'addtag', 'alloc')
    for var in kwargs['kwargs'].keys():
        if kwargs['kwargs'][var] and var in valid:
            cmd += ' --{0} {1}'.format(var, kwargs['kwargs'][var])
    result = __salt__['cmd.run_all'](cmd)
    state_std(kwargs, result)
    if result['retcode'] != 0 or result['stderr']:
        return result['stderr']
    out = result['stdout'].splitlines()
    vgdata = vgdisplay(vgname)
    vgdata['Output from vgcreate'] = out[0].strip()
    return vgdata
Ejemplo n.º 17
0
def chhomephone(name, homephone, **kwargs):
    '''
    Change the user's Home Phone

    CLI Example:

    .. code-block:: bash

        salt '*' user.chhomephone foo "7735551234"
    '''
    homephone = str(homephone)
    pre_info = _get_gecos(name)
    if not pre_info:
        return False
    if homephone == pre_info['homephone']:
        return True
    gecos_field = copy.deepcopy(pre_info)
    gecos_field['homephone'] = homephone
    cmd = 'usermod -c "{0}" {1}'.format(_build_gecos(gecos_field), name)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    post_info = info(name)
    if post_info['homephone'] != pre_info['homephone']:
        return str(post_info['homephone']) == homephone
    return False
Ejemplo n.º 18
0
def remove(name, user=None, conf_file=None, bin_env=None, **kwargs):
    '''
    Removes process/group from active config

    user
        user to run supervisorctl as
    conf_file
        path to supervisorctl config file
    bin_env
        path to supervisorctl bin or path to virtualenv with supervisor
        installed

    CLI Example:

    .. code-block:: bash

        salt '*' supervisord.remove <name>
    '''
    if name.endswith(':'):
        name = name[:-1]
    ret = __salt__['cmd.run_stdall'](
        _ctl_cmd('remove', name, conf_file, bin_env), runas=user
    )
    state_std(kwargs, ret)
    return _get_return(ret)
Ejemplo n.º 19
0
def chfullname(name, fullname, **kwargs):
    '''
    Change the user's Full Name

    CLI Example:

    .. code-block:: bash

        salt '*' user.chfullname foo "Foo Bar"
    '''
    fullname = str(fullname)
    pre_info = _get_gecos(name)
    if not pre_info:
        return False
    if fullname == pre_info['fullname']:
        return True
    gecos_field = copy.deepcopy(pre_info)
    gecos_field['fullname'] = fullname
    cmd = 'usermod -c "{0}" {1}'.format(_build_gecos(gecos_field), name)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    post_info = info(name)
    if post_info['fullname'] != pre_info['fullname']:
        return str(post_info['fullname']) == fullname
    return False
Ejemplo n.º 20
0
def chroomnumber(name, roomnumber, **kwargs):
    '''
    Change the user's Room Number

    CLI Example:

    .. code-block:: bash

        salt '*' user.chroomnumber foo 123
    '''
    roomnumber = str(roomnumber)
    pre_info = _get_gecos(name)
    if not pre_info:
        return False
    if roomnumber == pre_info['roomnumber']:
        return True
    gecos_field = copy.deepcopy(pre_info)
    gecos_field['roomnumber'] = roomnumber
    cmd = 'usermod -c "{0}" {1}'.format(_build_gecos(gecos_field), name)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    post_info = info(name)
    if post_info['roomnumber'] != pre_info['roomnumber']:
        return str(post_info['roomnumber']) == roomnumber
    return False
Ejemplo n.º 21
0
def remount(name, device, mkmnt=False, fstype='', opts='defaults', **kwargs):
    '''
    Attempt to remount a device, if the device is not already mounted, mount
    is called

    CLI Example:

    .. code-block:: bash

        salt '*' mount.remount /mnt/foo /dev/sdz1 True
    '''
    if isinstance(opts, string_types):
        opts = opts.split(',')
    mnts = active()
    if name in mnts:
        # The mount point is mounted, attempt to remount it with the given data
        if 'remount' not in opts:
            opts.append('remount')
        lopts = ','.join(opts)
        args = '-o {0}'.format(lopts)
        if fstype:
            args += ' -t {0}'.format(fstype)
        cmd = 'mount {0} {1} {2} '.format(args, device, name)
        out = __salt__['cmd.run_stdall'](cmd)
        state_std(kwargs, out)
        if out['retcode']:
            return out['stderr']
        return True
    # Mount a filesystem that isn't already
    return mount(name, device, mkmnt, fstype, opts)
Ejemplo n.º 22
0
def swapon(name, priority=None, **kwargs):
    '''
    Activate a swap disk

    CLI Example:

    .. code-block:: bash

        salt '*' mount.swapon /root/swapfile
    '''
    ret = {}
    on_ = swaps()
    if name in on_:
        ret['stats'] = on_[name]
        ret['new'] = False
        return ret
    cmd = 'swapon {0}'.format(name)
    if priority:
        cmd += ' -p {0}'.format(priority)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    on_ = swaps()
    if name in on_:
        ret['stats'] = on_[name]
        ret['new'] = True
        return ret
    return ret
Ejemplo n.º 23
0
def chhomephone(name, homephone, **kwargs):
    """
    Change the user's Home Phone

    CLI Example:

    .. code-block:: bash

        salt '*' user.chhomephone foo "7735551234"
    """
    homephone = str(homephone)
    pre_info = _get_gecos(name)
    if not pre_info:
        return False
    if homephone == pre_info["homephone"]:
        return True
    gecos_field = copy.deepcopy(pre_info)
    gecos_field["homephone"] = homephone
    cmd = 'usermod -c "{0}" {1}'.format(_build_gecos(gecos_field), name)
    result = __salt__["cmd.run_stdall"](cmd)
    state_std(kwargs, result)
    post_info = info(name)
    if post_info["homephone"] != pre_info["homephone"]:
        return str(post_info["homephone"]) == homephone
    return False
Ejemplo n.º 24
0
def chroomnumber(name, roomnumber, **kwargs):
    """
    Change the user's Room Number

    CLI Example:

    .. code-block:: bash

        salt '*' user.chroomnumber foo 123
    """
    roomnumber = str(roomnumber)
    pre_info = _get_gecos(name)
    if not pre_info:
        return False
    if roomnumber == pre_info["roomnumber"]:
        return True
    gecos_field = copy.deepcopy(pre_info)
    gecos_field["roomnumber"] = roomnumber
    cmd = 'usermod -c "{0}" {1}'.format(_build_gecos(gecos_field), name)
    result = __salt__["cmd.run_stdall"](cmd)
    state_std(kwargs, result)
    post_info = info(name)
    if post_info["roomnumber"] != pre_info["roomnumber"]:
        return str(post_info["roomnumber"]) == roomnumber
    return False
Ejemplo n.º 25
0
def chfullname(name, fullname, **kwargs):
    """
    Change the user's Full Name

    CLI Example:

    .. code-block:: bash

        salt '*' user.chfullname foo "Foo Bar"
    """
    fullname = str(fullname)
    pre_info = _get_gecos(name)
    if not pre_info:
        return False
    if fullname == pre_info["fullname"]:
        return True
    gecos_field = copy.deepcopy(pre_info)
    gecos_field["fullname"] = fullname
    cmd = 'usermod -c "{0}" {1}'.format(_build_gecos(gecos_field), name)
    result = __salt__["cmd.run_stdall"](cmd)
    state_std(kwargs, result)
    post_info = info(name)
    if post_info["fullname"] != pre_info["fullname"]:
        return str(post_info["fullname"]) == fullname
    return False
Ejemplo n.º 26
0
def install(pkg=None,
            dir=None,
            runas=None,
            **kwargs):
    '''
    Install an NPM package.

    If no directory is specified, the package will be installed globally. If
    no package is specified, the dependencies (from package.json) of the
    package in the given directory will be installed.

    pkg
        A package name in any format accepted by NPM, including a version
        identifier

    dir
        The target directory in which to install the package, or None for
        global installation

    runas
        The user to run NPM with

    CLI Example:

    .. code-block:: bash

        salt '*' npm.install coffee-script

        salt '*' npm.install [email protected]

    '''
    if not _valid_version():
        return '{0!r} is not available.'.format('npm.install')

    cmd = 'unbuffer npm install'		#'npm install --silent --json'

    if dir is None:
        cmd += ' --global'

    if pkg:
        cmd += ' "{0}"'.format(pkg)

    result = __salt__['cmd.run_stdall'](cmd, cwd=dir, runas=runas)
    state_std(kwargs, result)
    if result['retcode'] != 0:
        raise CommandExecutionError(result['stderr'])

    # npm >1.2.21 is putting the output to stderr even though retcode is 0
    npm_output = result['stdout'] or result['stderr']
    for line in npm_output.splitlines():
        if line.find(pkg) >= 0:
            return [{
                'name'		:	pkg,
                'version'	:	line[line.find(pkg)+len(pkg):line.find(' ')]	#EXAMPLE: [email protected] /usr/local/lib/node_modules/express
            }]

    return npm_output
Ejemplo n.º 27
0
def install(pkg=None, dir=None, runas=None, **kwargs):
    '''
    Install an NPM package.

    If no directory is specified, the package will be installed globally. If
    no package is specified, the dependencies (from package.json) of the
    package in the given directory will be installed.

    pkg
        A package name in any format accepted by NPM, including a version
        identifier

    dir
        The target directory in which to install the package, or None for
        global installation

    runas
        The user to run NPM with

    CLI Example:

    .. code-block:: bash

        salt '*' npm.install coffee-script

        salt '*' npm.install [email protected]

    '''
    if not _valid_version():
        return '{0!r} is not available.'.format('npm.install')

    cmd = 'unbuffer npm install'  #'npm install --silent --json'

    if dir is None:
        cmd += ' --global'

    if pkg:
        cmd += ' "{0}"'.format(pkg)

    result = __salt__['cmd.run_stdall'](cmd, cwd=dir, runas=runas)
    state_std(kwargs, result)
    if result['retcode'] != 0:
        raise CommandExecutionError(result['stderr'])

    # npm >1.2.21 is putting the output to stderr even though retcode is 0
    npm_output = result['stdout'] or result['stderr']
    for line in npm_output.splitlines():
        if line.find(pkg) >= 0:
            return [{
                'name': pkg,
                'version': line[line.find(pkg) + len(pkg):line.find(
                    ' '
                )]  #EXAMPLE: [email protected] /usr/local/lib/node_modules/express
            }]

    return npm_output
Ejemplo n.º 28
0
def freeze(bin_env=None, user=None, runas=None, cwd=None, **kwargs):
    '''
    Return a list of installed packages either globally or in the specified
    virtualenv

    bin_env
        path to pip bin or path to virtualenv. If doing an uninstall from
        the system python and want to use a specific pip bin (pip-2.7,
        pip-2.6, etc..) just specify the pip bin you want.
        If uninstalling from a virtualenv, just use the path to the virtualenv
        (/home/code/path/to/virtualenv/)
    user
        The user under which to run pip

    .. note::
        The ``runas`` argument is deprecated as of 0.16.2. ``user`` should be
        used instead.

    cwd
        Current working directory to run pip from

    CLI Example:

    .. code-block:: bash

        salt '*' pip.freeze /home/code/path/to/virtualenv/
    '''
    if runas is not None:
        # The user is using a deprecated argument, warn!
        salt.utils.warn_until(
            'Hydrogen',
            'The \'runas\' argument to pip.install is deprecated, and will be '
            'removed in Salt {version}. Please use \'user\' instead.')

    # "There can only be one"
    if runas is not None and user:
        raise CommandExecutionError(
            'The \'runas\' and \'user\' arguments are mutually exclusive. '
            'Please use \'user\' as \'runas\' is being deprecated.')

    # Support deprecated 'runas' arg
    elif runas is not None and not user:
        user = str(runas)

    cmd = [_get_pip_bin(bin_env), 'freeze']
    cmd_kwargs = dict(runas=user, cwd=cwd)
    if bin_env and os.path.isdir(bin_env):
        cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
    result = __salt__['cmd.run_stdall'](' '.join(cmd), **cmd_kwargs)
    state_std(kwargs, result)

    if result['retcode'] > 0:
        raise CommandExecutionError(result['stderr'])

    return result['stdout'].splitlines()
Ejemplo n.º 29
0
def set_hwclock(clock, **kwargs):
    '''
    Sets the hardware clock to be either UTC or localtime

    CLI Example:

    .. code-block:: bash

        salt '*' timezone.set_hwclock UTC
    '''
    timezone = get_zone()

    if 'Solaris' in __grains__['os_family']:
        if 'sparc' in __grains__['cpuarch']:
            return 'UTC is the only choice for SPARC architecture'
        if clock == 'localtime':
            cmd = 'rtc -z {0}'.format(timezone)
            result = __salt__['cmd.run_stdall'](cmd)
            state_std(kwargs, result)
            return True
        elif clock == 'UTC':
            cmd = 'rtc -z GMT'
            result = __salt__['cmd.run_stdall'](cmd)
            state_std(kwargs, result)
            return True
    else:
        zonepath = '/usr/share/zoneinfo/{0}'.format(timezone)

    if not os.path.exists(zonepath):
        return 'Zone does not exist: {0}'.format(zonepath)

    if 'Solaris' not in __grains__['os_family']:
        os.unlink('/etc/localtime')
        os.symlink(zonepath, '/etc/localtime')

    if 'Arch' in __grains__['os_family']:
        __salt__['file.sed'](
            '/etc/rc.conf', '^HARDWARECLOCK=.*', 'HARDWARECLOCK="{0}"'.format(
                clock))
    elif 'RedHat' in __grains__['os_family']:
        __salt__['file.sed'](
            '/etc/sysconfig/clock', '^ZONE=.*', 'ZONE="{0}"'.format(timezone))
    elif 'Suse' in __grains__['os_family']:
        __salt__['file.sed'](
            '/etc/sysconfig/clock', '^ZONE=.*', 'ZONE="{0}"'.format(timezone))
    elif 'Debian' in __grains__['os_family']:
        if clock == 'UTC':
            __salt__['file.sed']('/etc/default/rcS', '^UTC=.*', 'UTC=yes')
        elif clock == 'localtime':
            __salt__['file.sed']('/etc/default/rcS', '^UTC=.*', 'UTC=no')
    elif 'Gentoo' in __grains__['os_family']:
        __salt__['file.sed'](
            '/etc/conf.d/hwclock', '^clock=.*', 'clock="{0}"'.format(clock))

    return True
Ejemplo n.º 30
0
def set_hwclock(clock, **kwargs):
    '''
    Sets the hardware clock to be either UTC or localtime

    CLI Example:

    .. code-block:: bash

        salt '*' timezone.set_hwclock UTC
    '''
    timezone = get_zone()

    if 'Solaris' in __grains__['os_family']:
        if 'sparc' in __grains__['cpuarch']:
            return 'UTC is the only choice for SPARC architecture'
        if clock == 'localtime':
            cmd = 'rtc -z {0}'.format(timezone)
            result = __salt__['cmd.run_stdall'](cmd)
            state_std(kwargs, result)
            return True
        elif clock == 'UTC':
            cmd = 'rtc -z GMT'
            result = __salt__['cmd.run_stdall'](cmd)
            state_std(kwargs, result)
            return True
    else:
        zonepath = '/usr/share/zoneinfo/{0}'.format(timezone)

    if not os.path.exists(zonepath):
        return 'Zone does not exist: {0}'.format(zonepath)

    if 'Solaris' not in __grains__['os_family']:
        os.unlink('/etc/localtime')
        os.symlink(zonepath, '/etc/localtime')

    if 'Arch' in __grains__['os_family']:
        __salt__['file.sed']('/etc/rc.conf', '^HARDWARECLOCK=.*',
                             'HARDWARECLOCK="{0}"'.format(clock))
    elif 'RedHat' in __grains__['os_family']:
        __salt__['file.sed']('/etc/sysconfig/clock', '^ZONE=.*',
                             'ZONE="{0}"'.format(timezone))
    elif 'Suse' in __grains__['os_family']:
        __salt__['file.sed']('/etc/sysconfig/clock', '^ZONE=.*',
                             'ZONE="{0}"'.format(timezone))
    elif 'Debian' in __grains__['os_family']:
        if clock == 'UTC':
            __salt__['file.sed']('/etc/default/rcS', '^UTC=.*', 'UTC=yes')
        elif clock == 'localtime':
            __salt__['file.sed']('/etc/default/rcS', '^UTC=.*', 'UTC=no')
    elif 'Gentoo' in __grains__['os_family']:
        __salt__['file.sed']('/etc/conf.d/hwclock', '^clock=.*',
                             'clock="{0}"'.format(clock))

    return True
Ejemplo n.º 31
0
def _write_cron_lines(user, lines, **kwargs):
    '''
    Takes a list of lines to be committed to a user's crontab and writes it
    '''
    path = salt.utils.mkstemp()
    with salt.utils.fopen(path, 'w+') as fp_:
        fp_.writelines(lines)
    if __grains__['os'] == 'Solaris' and user != "root":
        __salt__['cmd.run']('chown {0} {1}'.format(user, path))
    ret = __salt__['cmd.run_stdall'](_get_cron_cmdstr(user, path))
    state_std(kwargs, ret)
    os.remove(path)
    return ret
Ejemplo n.º 32
0
def write_cron_file_verbose(user, path, **kwargs):
    '''
    Writes the contents of a file to a user's crontab and return error message on error

    CLI Example:

    .. code-block:: bash

        salt '*' cron.write_cron_file_verbose root /tmp/new_cron
    '''
    result = __salt__['cmd.run_stdall'](_get_cron_cmdstr(user, path))
    state_std(kwargs, result)
    return result
Ejemplo n.º 33
0
def delete(name, **kwargs):
    '''
    Remove the named group

    CLI Example:

    .. code-block:: bash

        salt '*' group.delete foo
    '''
    ret = __salt__['cmd.run_stdall']('groupdel {0}'.format(name))
    state_std(kwargs, ret)

    return not ret['retcode']
Ejemplo n.º 34
0
Archivo: gem.py Proyecto: zeus911/salt
def _gem(command, ruby=None, runas=None, **kwargs):
    cmdline = 'gem {command}'.format(command=command)
    if __salt__['rvm.is_installed'](runas=runas):
        return __salt__['rvm.do'](ruby, cmdline, runas=runas, **kwargs)

    if __salt__['rbenv.is_installed'](runas=runas):
        return __salt__['rbenv.do'](cmdline, runas=runas, **kwargs)

    ret = __salt__['cmd.run_stdall'](cmdline, runas=runas)
    state_std(kwargs, ret)
    if ret['retcode'] == 0:
        return ret['stdout']
    else:
        return False
Ejemplo n.º 35
0
def stop(name, **kwargs):
    '''
    Stop the specified service

    CLI Example:

    .. code-block:: bash

        salt '*' service.stop <service name>
    '''
    cmd = 'service {0} stop'.format(name)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 36
0
def full_restart(name, **kwargs):
    '''
    Do a full restart (stop/start) of the named service

    CLI Example:

    .. code-block:: bash

        salt '*' service.full_restart <service name>
    '''
    cmd = 'service {0} --full-restart'.format(name)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 37
0
def restart(name, **kwargs):
    '''
    Restart the named service

    CLI Example:

    .. code-block:: bash

        salt '*' service.restart <service name>
    '''
    cmd = 'service {0} restart'.format(name)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 38
0
def force_reload(name, **kwargs):
    '''
    Force-reload the named service

    CLI Example:

    .. code-block:: bash

        salt '*' service.force_reload <service name>
    '''
    cmd = 'service {0} force-reload'.format(name)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 39
0
def delete(name, **kwargs):
    '''
    Remove the named group

    CLI Example:

    .. code-block:: bash

        salt '*' group.delete foo
    '''
    ret = __salt__['cmd.run_stdall']('groupdel {0}'.format(name))
    state_std(kwargs, ret)

    return not ret['retcode']
Ejemplo n.º 40
0
def refresh_db(**kwargs):
    '''
    Since yum refreshes the database automatically, this runs a yum clean,
    so that the next yum operation will have a clean database

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.refresh_db
    '''
    cmd = 'yum -q clean dbcache'
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return True
Ejemplo n.º 41
0
def lvremove(lvname, vgname, **kwargs):
    '''
    Remove a given existing logical volume from a named existing volume group

    CLI Example:

    .. code-block:: bash

        salt '*' lvm.lvremove lvname vgname force=True
    '''
    cmd = 'lvremove -f {0}/{1}'.format(vgname, lvname)
    result = __salt__['cmd.run_all'](cmd)
    state_std(kwargs, result)
    out = result['stdout'].splitlines()
    return out.strip()
Ejemplo n.º 42
0
def start(name, **kwargs):
    '''
    Start the specified service

    CLI Example:

    .. code-block:: bash

        salt '*' service.start <service name>
    '''
    cmd = _service_cmd(name, 'start')

    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 43
0
def disable(name, **kwargs):
    '''
    Disable the named service to not start when the system boots

    CLI Example:

    .. code-block:: bash

        salt '*' service.disable <service name>
    '''
    if _untracked_custom_unit_found(name) or _unit_file_changed(name):
        systemctl_reload()
    result = __salt__['cmd.run_stdall'](_systemctl_cmd('disable', name))
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 44
0
def force_reload(name, **kwargs):
    '''
    Force-reload the specified service with systemd

    CLI Example:

    .. code-block:: bash

        salt '*' service.force_reload <service name>
    '''
    if _untracked_custom_unit_found(name) or _unit_file_changed(name):
        systemctl_reload()
    result = __salt__['cmd.run_stdall'](_systemctl_cmd('force-reload', name))
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 45
0
def refresh_db(**kwargs):
    '''
    Since yum refreshes the database automatically, this runs a yum clean,
    so that the next yum operation will have a clean database

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.refresh_db
    '''
    cmd = 'yum -q clean dbcache'
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return True
Ejemplo n.º 46
0
def force_reload(name, **kwargs):
    '''
    Force-reload the specified service with systemd

    CLI Example:

    .. code-block:: bash

        salt '*' service.force_reload <service name>
    '''
    if _untracked_custom_unit_found(name) or _unit_file_changed(name):
        systemctl_reload()
    result = __salt__['cmd.run_stdall'](_systemctl_cmd('force-reload', name))
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 47
0
def lvremove(lvname, vgname, **kwargs):
    '''
    Remove a given existing logical volume from a named existing volume group

    CLI Example:

    .. code-block:: bash

        salt '*' lvm.lvremove lvname vgname force=True
    '''
    cmd = 'lvremove -f {0}/{1}'.format(vgname, lvname)
    result = __salt__['cmd.run_all'](cmd)
    state_std(kwargs, result)
    out = result['stdout'].splitlines()
    return out.strip()
Ejemplo n.º 48
0
def disable(name, **kwargs):
    '''
    Disable the named service to not start when the system boots

    CLI Example:

    .. code-block:: bash

        salt '*' service.disable <service name>
    '''
    if _untracked_custom_unit_found(name) or _unit_file_changed(name):
        systemctl_reload()
    result = __salt__['cmd.run_stdall'](_systemctl_cmd('disable', name))
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 49
0
def reload_(name, **kwargs):
    '''
    Reload the named service

    CLI Example:

    .. code-block:: bash

        salt '*' service.reload <service name>
    '''
    cmd = _service_cmd(name, 'reload')

    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 50
0
def systemctl_reload(**kwargs):
    '''
    Reloads systemctl, an action needed whenever unit files are updated.

    CLI Example:

    .. code-block:: bash

        salt '*' service.systemctl_reload
    '''
    result = __salt__['cmd.run_stdall']('systemctl --system daemon-reload')
    state_std(kwargs, result)
    retcode = result['retcode']
    if retcode != 0:
        log.error('Problem performing systemctl daemon-reload')
    return retcode == 0
Ejemplo n.º 51
0
def vgremove(vgname, **kwargs):
    '''
    Remove an LVM volume group

    CLI Examples:

    .. code-block:: bash

        salt mymachine lvm.vgremove vgname
        salt mymachine lvm.vgremove vgname force=True
    '''
    cmd = 'vgremove -f {0}'.format(vgname)
    result = __salt__['cmd.run_all'](cmd)
    state_std(kwargs, result)
    out = result['stdout'].splitlines()
    return out.strip()
Ejemplo n.º 52
0
def disable(name, **kwargs):
    '''
    Disable the named service from starting on boot

    CLI Example:

    .. code-block:: bash

        salt '*' service.disable <service name>
    '''
    if _service_is_upstart(name):
        return _upstart_disable(name)
    executable = _get_service_exec()
    cmd = '{0} -f {1} remove'.format(executable, name)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 53
0
def enable(name, **kwargs):
    '''
    Enable the named service to start at boot

    CLI Example:

    .. code-block:: bash

        salt '*' service.enable <service name>
    '''
    if _service_is_upstart(name):
        return _upstart_enable(name)
    executable = _get_service_exec()
    cmd = '{0} -f {1} defaults'.format(executable, name)
    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']
Ejemplo n.º 54
0
def reload_(name, **kwargs):
    '''
    Reload the named service

    CLI Example:

    .. code-block:: bash

        salt '*' service.reload <service name>
    '''
    if _service_is_upstart(name):
        cmd = 'reload {0}'.format(name)
    else:
        cmd = '/sbin/service {0} reload'.format(name)

    result = __salt__['cmd.run_stdall'](cmd)
    state_std(kwargs, result)
    return not result['retcode']