Example #1
0
def load_states():
    '''
    This loads our states into the salt __context__
    '''
    states = {}

    # the loader expects to find pillar & grian data
    __opts__['grains'] = __grains__
    __opts__['pillar'] = __pillar__

    # we need to build our own loader so that we can process the virtual names
    # in our own way.
    load = _create_loader(__opts__, 'states', 'states')
    load.load_modules()
    for mod in load.modules:
        module_name = mod.__name__.rsplit('.', 1)[-1]

        (virtual_ret, virtual_name) = load.process_virtual(mod, module_name)

        # if the module returned a True value and a new name use that
        # otherwise use the default module name
        if virtual_ret and virtual_name != module_name:
            module_name = virtual_name

        # load our functions from the module, pass None in as the module_name
        # so that our function names come back unprefixed
        states[module_name] = load.load_functions(mod, None)

    __context__['pyobjects_states'] = states
Example #2
0
def __init__(opts):
    """Generate a state function for each ansible module found. """

    # ask salt to load and initialize the ansmod salt module
    from salt.loader import _create_loader, loaded_base_name
    tag = 'module'
    modname = 'ansmod'
    load = _create_loader(opts, 'modules', tag)
    load.gen_module(modname, {})

    # get the loaded ansmod module
    import sys
    try:
        ansmod = sys.modules[loaded_base_name + '.' + tag + '.' + modname]
    except KeyError:
        log.warn("Make sure the %s salt module's been loaded correctly!" %
                 modname)
    else:
        # populate the state functions in this module
        mod = globals()
        for state in ansmod.STATE_NAMES:
            mod[state] = ansmod._state_func

        # make the use of the shell module actually invokes the
        # command module instead.
        ansmod.STATE_NAMES['shell'] = 'command'
Example #3
0
def _get_local_grains():
    """
    Return the salt grains for this host that we are running
    on.  If we support SELinux in the future this may need
    to be moved into a cthulhu RPC as the apache worker may
    not have the right capabilities to query all the grains.
    """
    # Stash grains as an attribute of this function
    if not hasattr(_get_local_grains, 'grains'):

        # >> work around salt issue #11402
        import __main__ as main
        main.__file__ = 'workaround'
        # <<

        # Use salt to get an interesting subset of the salt grains (getting
        # everything is a bit slow)
        grains = {}
        c = master_config(config.get('cthulhu', 'salt_config_path'))
        l = _create_loader(c, 'grains', 'grain')
        funcs = l.gen_functions()
        for key in [k for k in funcs.keys() if k.startswith('core.')]:
            ret = funcs[key]()
            if isinstance(ret, dict):
                grains.update(ret)
        _get_local_grains.grains = grains
    else:
        grains = _get_local_grains.grains

    return grains
Example #4
0
def __init__(opts):
    """Generate a state function for each ansible module found. """

    # ask salt to load and initialize the ansmod salt module
    from salt.loader import _create_loader, loaded_base_name
    tag = 'module'
    modname = 'ansmod'
    load = _create_loader(opts, 'modules', tag)
    load.gen_module(modname, {})

    # get the loaded ansmod module
    import sys
    try:
        ansmod = sys.modules[loaded_base_name+'.'+tag+'.'+modname]
    except KeyError:
        log.warn("Make sure the %s salt module's been loaded correctly!" \
                  % modname)
    else:
        # populate the state functions in this module
        mod = globals()
        for state in ansmod.STATE_NAMES:
            mod[state] = ansmod._state_func

        # make the use of the shell module actually invokes the
        # command module instead.
        ansmod.STATE_NAMES['shell'] = 'command'
Example #5
0
def _get_local_grains():
    """
    Return the salt grains for this host that we are running
    on.  If we support SELinux in the future this may need
    to be moved into a cthulhu RPC as the apache worker may
    not have the right capabilities to query all the grains.
    """
    # Stash grains as an attribute of this function
    if not hasattr(_get_local_grains, 'grains'):

        # >> work around salt issue #11402
        import __main__ as main
        main.__file__ = 'workaround'
        # <<

        # Use salt to get an interesting subset of the salt grains (getting
        # everything is a bit slow)
        grains = {}
        c = master_config(config.get('cthulhu', 'salt_config_path'))
        l = _create_loader(c, 'grains', 'grain')
        funcs = l.gen_functions()
        for key in [k for k in funcs.keys() if k.startswith('core.')]:
            ret = funcs[key]()
            if isinstance(ret, dict):
                grains.update(ret)
        _get_local_grains.grains = grains
    else:
        grains = _get_local_grains.grains

    return grains
def managed(name, type, enabled=True, **kwargs):
    '''
    Ensure that the named interface is configured properly.

    name
        The name of the interface to manage

    type
        Type of interface and configuration.

    enabled
        Designates the state of this interface.

    kwargs
        The IP parameters for this interface.

    '''
    # For this function we are purposefully overwriting a bif
    # to enhance the user experience. This does not look like
    # it will cause a problem. Just giving a heads up in case
    # it does create a problem.
    ret = {
        'name': name,
        'changes': {},
        'result': True,
        'comment': 'Interface {0} is up to date.'.format(name),
    }
    if 'test' not in kwargs:
        kwargs['test'] = __opts__.get('test', False)

    # Build interface
    try:
        old = __salt__['ip.get_interface'](name)
        new = __salt__['ip.build_interface'](name, type, enabled, **kwargs)
        if kwargs['test']:
            if old == new:
                pass
            if not old and new:
                ret['result'] = None
                ret['comment'] = 'Interface {0} is set to be ' \
                                 'added.'.format(name)
            elif old != new:
                diff = difflib.unified_diff(old, new, lineterm='')
                ret['result'] = None
                ret['comment'] = 'Interface {0} is set to be ' \
                                 'updated.'.format(name)
                ret['changes']['interface'] = '\n'.join(diff)
        else:
            if not old and new:
                ret['comment'] = 'Interface {0} ' \
                                 'added.'.format(name)
                ret['changes']['interface'] = 'Added network interface.'
            elif old != new:
                diff = difflib.unified_diff(old, new, lineterm='')
                ret['comment'] = 'Interface {0} ' \
                                 'updated.'.format(name)
                ret['changes']['interface'] = '\n'.join(diff)
    except AttributeError as error:
        ret['result'] = False
        ret['comment'] = str(error)
        return ret

    # Setup up bond modprobe script if required
    if type == 'bond':
        try:
            old = __salt__['ip.get_bond'](name)
            new = __salt__['ip.build_bond'](name, **kwargs)
            if kwargs['test']:
                if old == new:
                    pass
                if not old and new:
                    ret['result'] = None
                    ret['comment'] = 'Bond interface {0} is set to be ' \
                                     'added.'.format(name)
                elif old != new:
                    diff = difflib.unified_diff(old, new, lineterm='')
                    ret['result'] = None
                    ret['comment'] = 'Bond interface {0} is set to be ' \
                                     'updated.'.format(name)
                    ret['changes']['bond'] = '\n'.join(diff)
            else:
                if not old and new:
                    ret['comment'] = 'Bond interface {0} ' \
                                     'added.'.format(name)
                    ret['changes']['bond'] = 'Added bond {0}.'.format(name)
                elif old != new:
                    diff = difflib.unified_diff(old, new, lineterm='')
                    ret['comment'] = 'Bond interface {0} ' \
                                     'updated.'.format(name)
                    ret['changes']['bond'] = '\n'.join(diff)
        except AttributeError as error:
            #TODO Add a way of reversing the interface changes.
            ret['result'] = False
            ret['comment'] = str(error)
            return ret

    if kwargs['test']:
        return ret

    # Bring up/shutdown interface
    try:
        # Get Interface current status
        interfaces = salt.utils.network.interfaces()
        interface_status = False
        if name in interfaces:
            interface_status = interfaces[name].get('up')
        else:
            for iface in interfaces:
                if 'secondary' in interfaces[iface]:
                    for second in interfaces[iface]['secondary']:
                        if second.get('label', '') == 'name':
                            interface_status = True
        if enabled:
            if interface_status:
                if ret['changes']:
                    # Interface should restart to validate if it's up
                    __salt__['ip.down'](name, type)
                    __salt__['ip.up'](name, type)
                    ret['changes']['status'] = 'Interface {0} restart to validate'.format(name)
                    return ret
            else:
                __salt__['ip.up'](name, type)
                ret['changes']['status'] = 'Interface {0} is up'.format(name)
        else:
            if interface_status:
                __salt__['ip.down'](name, type)
                ret['changes']['status'] = 'Interface {0} down'.format(name)
    except Exception as error:
        ret['result'] = False
        ret['comment'] = str(error)
        return ret

    load = _create_loader(__opts__, 'grains', 'grain', ext_dirs=False)
    grains_info = load.gen_grains()
    __grains__.update(grains_info)
    __salt__['saltutil.refresh_modules']()
    return ret
Example #7
0
def managed(name, type, enabled=True, **kwargs):
    '''
    Ensure that the named interface is configured properly.

    name
        The name of the interface to manage

    type
        Type of interface and configuration.

    enabled
        Designates the state of this interface.

    kwargs
        The IP parameters for this interface.

    '''
    # For this function we are purposefully overwriting a bif
    # to enhance the user experience. This does not look like
    # it will cause a problem. Just giving a heads up in case
    # it does create a problem.

    ret = {
        'name': name,
        'changes': {},
        'result': True,
        'comment': 'Interface {0} is up to date.'.format(name),
    }
    if not 'test' in kwargs:
        kwargs['test'] = __opts__.get('test', False)

    # Build interface
    try:
        old = __salt__['ip.get_interface'](name)
        new = __salt__['ip.build_interface'](name, type, enabled, **kwargs)
        if kwargs['test']:
            if old == new:
                pass
            if not old and new:
                ret['result'] = None
                ret['comment'] = 'Interface {0} is set to be ' \
                                 'added.'.format(name)
            elif old != new:
                diff = difflib.unified_diff(old, new)
                ret['result'] = None
                ret['comment'] = 'Interface {0} is set to be ' \
                                 'updated.'.format(name)
                ret['changes']['interface'] = ''.join(diff)
        else:
            if not old and new:
                ret['comment'] = 'Interface {0} ' \
                                 'added.'.format(name)
                ret['changes']['interface'] = 'Added network interface.'
            elif old != new:
                diff = difflib.unified_diff(old, new)
                ret['comment'] = 'Interface {0} ' \
                                 'updated.'.format(name)
                ret['changes']['interface'] = ''.join(diff)
    except AttributeError as error:
        ret['result'] = False
        ret['comment'] = error.message
        return ret

    # Setup up bond modprobe script if required
    if type == 'bond':
        try:
            old = __salt__['ip.get_bond'](name)
            new = __salt__['ip.build_bond'](name, **kwargs)
            if kwargs['test']:
                if old == new:
                    pass
                if not old and new:
                    ret['result'] = None
                    ret['comment'] = 'Bond interface {0} is set to be ' \
                                     'added.'.format(name)
                elif old != new:
                    diff = difflib.unified_diff(old, new)
                    ret['result'] = None
                    ret['comment'] = 'Bond interface {0} is set to be ' \
                                     'updated.'.format(name)
                    ret['changes']['bond'] = ''.join(diff)
            else:
                if not old and new:
                    ret['comment'] = 'Bond interface {0} ' \
                                     'added.'.format(name)
                    ret['changes']['bond'] = 'Added bond {0}.'.format(name)
                elif old != new:
                    diff = difflib.unified_diff(old, new)
                    ret['comment'] = 'Bond interface {0} ' \
                                     'updated.'.format(name)
                    ret['changes']['bond'] = ''.join(diff)
        except AttributeError as error:
            #TODO Add a way of reversing the interface changes.
            ret['result'] = False
            ret['comment'] = error.message
            return ret

    if kwargs['test']:
        return ret

    # Bring up/shutdown interface
    try:
        if enabled:
            __salt__['ip.up'](name, type)
        else:
            __salt__['ip.down'](name, type)
    except Exception as error:
        ret['result'] = False
        ret['comment'] = error.message
        return ret

    load = _create_loader(__opts__, 'grains', 'grain', ext_dirs=False)
    grains_info = load.gen_grains()
    __grains__.update(grains_info)
    __salt__['saltutil.refresh_modules']()
    return ret
Example #8
0
def managed(name, type, enabled=True, **kwargs):
    '''
    Ensure that the named interface is configured properly.

    name
        The name of the interface to manage

    type
        Type of interface and configuration.

    enabled
        Designates the state of this interface.

    kwargs
        The IP parameters for this interface.

    '''
    # For this function we are purposefully overwriting a bif
    # to enhance the user experience. This does not look like
    # it will cause a problem. Just giving a heads up in case
    # it does create a problem.

    ret = {
        'name': name,
        'changes': {},
        'result': True,
        'comment': 'Interface {0} is up to date.'.format(name),
    }
    kwargs['test'] = __opts__['test']

    # Build interface
    try:
        old = __salt__['ip.get_interface'](name)
        new = __salt__['ip.build_interface'](name, type, enabled, **kwargs)
        if __opts__['test']:
            if old == new:
                pass
            if not old and new:
                ret['result'] = None
                ret['comment'] = 'Interface {0} is set to be ' \
                                 'added.'.format(name)
            elif old != new:
                diff = difflib.unified_diff(old, new)
                ret['result'] = None
                ret['comment'] = 'Interface {0} is set to be ' \
                                 'updated.'.format(name)
                ret['changes']['interface'] = ''.join(diff)
        else:
            if not old and new:
                ret['changes']['interface'] = 'Added network interface.'
            elif old != new:
                diff = difflib.unified_diff(old, new)
                ret['changes']['interface'] = ''.join(diff)
    except AttributeError as error:
        ret['result'] = False
        ret['comment'] = error.message
        return ret

    # Setup up bond modprobe script if required
    if type == 'bond':
        try:
            old = __salt__['ip.get_bond'](name)
            new = __salt__['ip.build_bond'](name, **kwargs)
            if __opts__['test']:
                if old == new:
                    pass
                if not old and new:
                    ret['result'] = None
                    ret['comment'] = 'Bond interface {0} is set to be ' \
                                     'added.'.format(name)
                elif old != new:
                    diff = difflib.unified_diff(old, new)
                    ret['result'] = None
                    ret['comment'] = 'Bond interface {0} is set to be ' \
                                     'updated.'.format(name)
                    ret['changes']['bond'] = ''.join(diff)
            else:
                if not old and new:
                    ret['changes']['bond'] = 'Added bond {0}.'.format(name)
                elif old != new:
                    diff = difflib.unified_diff(old, new)
                    ret['changes']['bond'] = ''.join(diff)
        except AttributeError as error:
            #TODO Add a way of reversing the interface changes.
            ret['result'] = False
            ret['comment'] = error.message
            return ret

    if __opts__['test']:
        return ret

    # Bring up/shutdown interface
    try:
        if enabled:
            __salt__['ip.up'](name, type)
        else:
            __salt__['ip.down'](name, type)
    except Exception as error:
        ret['result'] = False
        ret['comment'] = error.message
        return ret

    load = _create_loader(__opts__, 'grains', 'grain', ext_dirs=False)
    grains_info = load.gen_grains()
    __grains__.update(grains_info)
    __salt__['saltutil.refresh_modules']()
    return ret
Example #9
0
def managed(name, type, enabled=True, **kwargs):
    """
    Ensure that the named interface is configured properly.

    name
        The name of the interface to manage

    type
        Type of interface and configuration.

    enabled
        Designates the state of this interface.

    kwargs
        The IP parameters for this interface.

    """
    # For this function we are purposefully overwriting a bif
    # to enhance the user experience. This does not look like
    # it will cause a problem. Just giving a heads up in case
    # it does create a problem.

    ret = {"name": name, "changes": {}, "result": True, "comment": "Interface {0} is up to date.".format(name)}
    kwargs["test"] = __opts__["test"]

    # Build interface
    try:
        old = __salt__["ip.get_interface"](name)
        new = __salt__["ip.build_interface"](name, type, enabled, **kwargs)
        if __opts__["test"]:
            if old == new:
                pass
            if not old and new:
                ret["result"] = None
                ret["comment"] = "Interface {0} is set to be " "added.".format(name)
            elif old != new:
                diff = difflib.unified_diff(old, new)
                ret["result"] = None
                ret["comment"] = "Interface {0} is set to be " "updated.".format(name)
                ret["changes"]["interface"] = "".join(diff)
        else:
            if not old and new:
                ret["changes"]["interface"] = "Added network interface."
            elif old != new:
                diff = difflib.unified_diff(old, new)
                ret["changes"]["interface"] = "".join(diff)
    except AttributeError as error:
        ret["result"] = False
        ret["comment"] = error.message
        return ret

    # Setup up bond modprobe script if required
    if type == "bond":
        try:
            old = __salt__["ip.get_bond"](name)
            new = __salt__["ip.build_bond"](name, **kwargs)
            if __opts__["test"]:
                if old == new:
                    pass
                if not old and new:
                    ret["result"] = None
                    ret["comment"] = "Bond interface {0} is set to be " "added.".format(name)
                elif old != new:
                    diff = difflib.unified_diff(old, new)
                    ret["result"] = None
                    ret["comment"] = "Bond interface {0} is set to be " "updated.".format(name)
                    ret["changes"]["bond"] = "".join(diff)
            else:
                if not old and new:
                    ret["changes"]["bond"] = "Added bond {0}.".format(name)
                elif old != new:
                    diff = difflib.unified_diff(old, new)
                    ret["changes"]["bond"] = "".join(diff)
        except AttributeError as error:
            # TODO Add a way of reversing the interface changes.
            ret["result"] = False
            ret["comment"] = error.message
            return ret

    if __opts__["test"]:
        return ret

    # Bring up/shutdown interface
    try:
        if enabled:
            __salt__["ip.up"](name, type)
        else:
            __salt__["ip.down"](name, type)
    except Exception as error:
        ret["result"] = False
        ret["comment"] = error.message
        return ret

    load = _create_loader(__opts__, "grains", "grain", ext_dirs=False)
    grains_info = load.gen_grains()
    __grains__.update(grains_info)
    __salt__["saltutil.refresh_modules"]()
    return ret