Example #1
0
    def __copy_sysctl(self):
        '''
        Copies an existing sysconf file and returns temp file path. Copied
        file will be restored in tearDown
        '''
        # Create new temporary file path and open needed files
        org_conf = fopen(CONFIG, 'r')
        temp_path = mkstemp()
        temp_sysconf = open(temp_path, 'w')

        # write sysctl lines to temp file
        for line in org_conf:
            temp_sysconf.write(line)
        org_conf.close()
        temp_sysconf.close()

        return temp_path
Example #2
0
    def __copy_sysctl(self):
        '''
        Copies an existing sysconf file and returns temp file path. Copied
        file will be restored in tearDown
        '''
        # Create new temporary file path and open needed files
        org_conf = fopen(CONFIG, 'r')
        temp_path = mkstemp()
        temp_sysconf = open(temp_path, 'w')

        # write sysctl lines to temp file
        for line in org_conf:
            temp_sysconf.write(line)
        org_conf.close()
        temp_sysconf.close()

        return temp_path
Example #3
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:
        stderrs = []

        # if the statefile provides multiple identities, they need to be tried
        # (but also allow a string instead of a list)
        if not isinstance(identity, list):
            # force it into a list
            identity = [identity]

        # try each of the identities, independently
        for id_file in identity:
            env = {'GIT_IDENTITY': id_file}

            # copy wrapper to area accessible by ``runas`` user
            # currently no suppport in windows for wrapping git ssh
            if not utils.is_windows():
                ssh_id_wrapper = os.path.join(utils.templates.TEMPLATE_DIRNAME,
                                              'git/ssh-id-wrapper')
                tmp_file = utils.mkstemp()
                utils.files.copyfile(ssh_id_wrapper, tmp_file)
                os.chmod(tmp_file, 0o500)
                os.chown(tmp_file, __salt__['file.user_to_uid'](runas), -1)
                env['GIT_SSH'] = tmp_file

            try:
                result = __salt__['cmd.run_all'](cmd,
                                                 cwd=cwd,
                                                 runas=runas,
                                                 output_loglevel='quiet',
                                                 env=env,
                                                 python_shell=False,
                                                 **kwargs)
            finally:
                if 'GIT_SSH' in env:
                    os.remove(env['GIT_SSH'])

            # if the command was successful, no need to try additional IDs
            if result['retcode'] == 0:
                return result['stdout']
            else:
                stderr = _remove_sensitive_data(result['stderr'])
                stderrs.append(stderr)

        # we've tried all IDs and still haven't passed, so error out
        raise CommandExecutionError("\n\n".join(stderrs))

    else:
        result = __salt__['cmd.run_all'](cmd,
                                         cwd=cwd,
                                         runas=runas,
                                         output_loglevel='quiet',
                                         env=env,
                                         python_shell=False,
                                         **kwargs)
        retcode = result['retcode']

        if retcode == 0:
            return result['stdout']
        else:
            stderr = _remove_sensitive_data(result['stderr'])
            raise CommandExecutionError(
                'Command {0!r} failed. Stderr: {1!r}'.format(cmd, stderr))
Example #4
0
def file(name,
         source_hash='',
         user='******',
         template=None,
         context=None,
         replace=True,
         defaults=None,
         env=None,
         backup='',
         **kwargs):
    '''
    Provides file.managed-like functionality (templating, etc.) for a pre-made
    crontab file, to be assigned to a given user.

    name
        The source file to be used as the crontab. This source file can be
        hosted on either the salt master server, or on an HTTP or FTP server.
        For files hosted on the salt file server, if the file is located on
        the master in the directory named spam, and is called eggs, the source
        string is salt://spam/eggs.

        If the file is hosted on a HTTP or FTP server then the source_hash
        argument is also required

    source_hash
        This can be either a file which contains a source hash string for
        the source, or a source hash string. The source hash string is the
        hash algorithm followed by the hash of the file:
        md5=e138491e9d5b97023cea823fe17bac22

    user
        The user to whom the crontab should be assigned. This defaults to
        root.

    template
        If this setting is applied then the named templating engine will be
        used to render the downloaded file. Currently, jinja and mako are
        supported.

    context
        Overrides default context variables passed to the template.

    replace
        If the crontab should be replaced, if False then this command will
        be ignored if a crontab exists for the specified user. Default is True.

    defaults
        Default context passed to the template.

    backup
        Overrides the default backup mode for the user's crontab.
    '''
    # Initial set up
    mode = __salt__['config.manage_mode'](600)
    owner, group, crontab_dir = _get_cron_info()

    cron_path = mkstemp()
    with fopen(cron_path, 'w+') as fp_:
        fp_.write(__salt__['cron.raw_cron'](user))

    ret = {'changes': {}, 'comment': '', 'name': name, 'result': True}

    # Avoid variable naming confusion in below module calls, since ID
    # delclaration for this state will be a source URI.
    source = name

    if env is None:
        env = kwargs.get('__env__', 'base')

    if not replace and os.stat(cron_path).st_size > 0:
        ret['comment'] = 'User {0} already has a crontab. No changes ' \
                         'made'.format(user)
        os.unlink(cron_path)
        return ret

    if __opts__['test']:
        fcm = __salt__['file.check_managed'](
            cron_path,
            source,
            source_hash,
            owner,
            group,
            mode,
            template,
            False,  # makedirs = False
            context,
            defaults,
            env,
            **kwargs)
        ret['result'], ret['comment'] = fcm
        os.unlink(cron_path)
        return ret

    # If the source is a list then find which file exists
    source, source_hash = __salt__['file.source_list'](source, source_hash,
                                                       env)

    # Gather the source file from the server
    sfn, source_sum, comment = __salt__['file.get_managed'](
        cron_path, template, source, source_hash, owner, group, mode, env,
        context, defaults, **kwargs)
    if comment:
        ret['comment'] = comment
        ret['result'] = False
        os.unlink(cron_path)
        return ret

    ret = __salt__['file.manage_file'](cron_path, sfn, ret, source, source_sum,
                                       owner, group, mode, env, backup)
    if ret['changes']:
        ret['changes'] = {'diff': ret['changes']['diff']}
        ret['comment'] = 'Crontab for user {0} was updated'.format(user)
    elif ret['result']:
        ret['comment'] = 'Crontab for user {0} is in the correct ' \
                         'state'.format(user)

    cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path)
    if cron_ret['retcode']:
        ret['comment'] = 'Unable to update user {0} crontab {1}.' \
                         ' Error: {2}'.format(user, cron_path, cron_ret['stderr'])
        ret['result'] = False

    os.unlink(cron_path)
    return ret
Example #5
0
def file(name,
         source_hash='',
         user='******',
         template=None,
         context=None,
         replace=True,
         defaults=None,
         env=None,
         backup='',
         **kwargs):
    '''
    Provides file.managed-like functionality (templating, etc.) for a pre-made
    crontab file, to be assigned to a given user.

    name
        The source file to be used as the crontab. This source file can be
        hosted on either the salt master server, or on an http or ftp server.
        For files hosted on the salt file server, if the file is located on
        the master in the directory named spam, and is called eggs, the source
        string is salt://spam/eggs.

        If the file is hosted on a http or ftp server then the source_hash
        argument is also required

    source_hash
        This can be either a file which contains a source hash string for
        the source, or a source hash string. The source hash string is the
        hash algorithm followed by the hash of the file:
        md5=e138491e9d5b97023cea823fe17bac22

    user
        The user to whome the crontab should be assigned. This defaults to
        root.

    template
        If this setting is applied then the named templating engine will be
        used to render the downloaded file. Currently, jinja and mako are
        supported.

    context
        Overrides default context variables passed to the template.

    replace
        If the crontab should be replaced, if False then this command will
        be ignored if a crontab exists for the specified user. Default is True.

    defaults
        Default context passed to the template.

    backup
        Overrides the default backup mode for the user's crontab.
    '''
    # Initial set up
    mode = __salt__['config.manage_mode'](600)
    owner, group, crontab_dir = _get_cron_info()

    cron_path = mkstemp()
    with open(cron_path, 'w+') as fp_:
        fp_.write(__salt__['cron.raw_cron'](user))

    ret = {'changes': {},
           'comment': '',
           'name': name,
           'result': True}

    # Avoid variable naming confusion in below module calls, since ID
    # delclaration for this state will be a source URI.
    source = name

    if env is None:
        env = kwargs.get('__env__', 'base')

    if not replace and os.stat(cron_path).st_size > 0:
        ret['comment'] = 'User {0} already has a crontab. No changes ' \
                         'made'.format(user)
        os.unlink(cron_path)
        return ret

    if __opts__['test']:
        fcm = __salt__['file.check_managed'](cron_path,
                                             source,
                                             source_hash,
                                             owner,
                                             group,
                                             mode,
                                             template,
                                             False,  # makedirs = False
                                             context,
                                             defaults,
                                             env,
                                             **kwargs
                                             )
        ret['result'], ret['comment'] = fcm
        os.unlink(cron_path)
        return ret

    # If the source is a list then find which file exists
    source, source_hash = __salt__['file.source_list'](source,
                                                       source_hash,
                                                       env)

    # Gather the source file from the server
    sfn, source_sum, comment = __salt__['file.get_managed'](cron_path,
                                                            template,
                                                            source,
                                                            source_hash,
                                                            owner,
                                                            group,
                                                            mode,
                                                            env,
                                                            context,
                                                            defaults,
                                                            **kwargs
                                                            )
    if comment:
        ret['comment'] = comment
        ret['result'] = False
        os.unlink(cron_path)
        return ret

    ret = __salt__['file.manage_file'](cron_path,
                                       sfn,
                                       ret,
                                       source,
                                       source_sum,
                                       owner,
                                       group,
                                       mode,
                                       env,
                                       backup)
    if not __salt__['cron.write_cron_file'](user, cron_path):
        ret['comment'] = 'Crontab file updated, but was unable to ' \
                         'update cron daemon'
        ret['result'] = False
    os.unlink(cron_path)
    return ret