Пример #1
0
def get_interface_without_service_policy(device,
                                         interface_type,
                                         virtual_interface=False):
    """ Find a interface without service-policy

        Args:
            device (`obj`): Device object
            interface_type (`str`): Interface type
            virtual_interface ('bool'): flag for matching virtual interfaces

        Returns:
            None
            interface (`str`): Interface name

        Raises:
            None
    """
    if not virtual_interface:
        p = re.compile(r"interface +(?P<intf>(?!\S+\.\S*)\S+)")
    else:
        p = re.compile(r"interface +(?P<intf>\S+)")

    config_dict = get_running_config_section_dict(device, "interface")
    for intf, config in config_dict.items():
        if intf.startswith("interface " + interface_type):
            cfg = "\n".join(config)
            if "service-policy" not in cfg:
                try:
                    return p.search(intf).groupdict()["intf"]
                except AttributeError:
                    continue
    else:
        return
Пример #2
0
def verify_interface_description_in_running_config(device, interface,
                                                   description):
    """Verify interface description in show running-config

        Args:
            device (`obj`): Device object
            interface (`str`): Interface name
            description (`str`): Interface description

        Returns:
            result(`bool`): verify result
    """
    try:
        output = get_running_config_section_dict(device, interface + "$")
    except Exception as e:
        log.error(str(e))
        raise Exception(
            "Failed to find interface {} through show running-config".format(
                interface))

    intf = "interface {}".format(interface)
    desc = "description {}".format(description)
    try:
        result = isinstance(output[intf][desc], dict)
    except KeyError:
        return False

    return result
Пример #3
0
def verify_vrf_description_in_running_config(device, vrf, description):
    """Verify vrf description in show running-config

        Args:
            device (`obj`): Device object
            vrf (`str`): VRF name
            description (`str`): Description

        Returns:
            True
            False

        Raises:
            Exception
            KeyError
    """
    try:
        output = get_running_config_section_dict(device, vrf + "$")
    except Exception as e:
        log.error(str(e))
        raise Exception(
            "Failed to find vrf {vrf} through show running-config".format(
                vrf=vrf))

    vrf = "vrf definition {vrf}".format(vrf=vrf)
    desc = "description {description}".format(description=description)
    try:
        result = isinstance(output[vrf][desc], dict)
    except KeyError:
        return False

    return result
Пример #4
0
def get_router_ospf_section_running_config(device, ospf_process_id):
    """ Get router OSPF section from running-config
        Args:
            device ('obj'): Device object
            ospf_process_id ('int'): OSPF router process id
        Returns:
            Dict with section
    """

    section = "router ospf {ospf_process_id}".format(
        ospf_process_id=ospf_process_id)
    return get_running_config_section_dict(device=device, section=section)
Пример #5
0
def get_mpls_interface_ldp_configured(device):
    """ Get interfaces which have ldp configured from 'show run'

        Args:
            device ('obj'): Device object
        Returns:
            interface address
    """
    interfaces = []
    intf_dict = get_running_config_section_dict(device, "interface")

    p = re.compile(r"^interface +(?P<name>[\S\s]+)$")
    for intf, data_dict in intf_dict.items():
        if "mpls label protocol ldp" in data_dict:
            m = p.match(intf)
            interfaces.append(m.groupdict()["name"])
    return interfaces
Пример #6
0
def get_segment_routing_sid_map_configuration(device, address_family="ipv4"):
    """ Get Segment routing SID map configuration

        Args:
            device ('str'): Device str
            address_family ('str'): Address family
        Returns:
            Dictionary with ip address as key and sid as value
            ex.)
                {
                    '192.168.1.1': '1',
                    '192.168.1.2': '2'
                }
    """
    out = get_running_config_section_dict(
        device=device, section="segment-routing"
    )

    sid_dict = {}

    if not out:
        return None

    p1 = re.compile(r"^(?P<ip_address>\S+) index (?P<sid>\d+) range \d+$")

    connected_prefix_sid_maps = out["segment-routing mpls"][
        "connected-prefix-sid-map"
    ]["address-family {}".format(address_family)].keys()

    for key in connected_prefix_sid_maps:
        key = key.strip()
        m = p1.match(key)
        if m:
            group = m.groupdict()
            sid_dict.update({group["ip_address"]: group["sid"]})
            continue

    return sid_dict
Пример #7
0
def is_bgp_import_path_selection(device,
                                 vrf,
                                 selection_type,
                                 max_time=30,
                                 check_interval=10):
    """ Verifies that import path selection of type is in running
        config

        Args:
            device('obj'): device to use
            vrf('str'): vrf name
            selection_type('str'): import path selection type to verify
            max_time('int'): max time to wait
            check_interval('int'): how often to check        
        Returns:
            True
            False
        Raises:
            None
    """
    options = "vrf {}".format(vrf)

    log.info('Verifying "import path selection {}" is configured'.format(
        selection_type))

    timeout = Timeout(max_time, check_interval)
    while timeout.iterate():
        out = get_running_config_section_dict(device,
                                              section="router bgp",
                                              options=options)
        if has_configuration(
                out, "import path selection {}".format(selection_type)):
            return True
        timeout.sleep()

    return False
Пример #8
0
def configure_shut_bgp_neighbors(device,
                                 bgp_as,
                                 neighbors=None,
                                 address_family=None,
                                 vrf=None,
                                 noshut=False):
    """ Configures shut/enable on bgp neighbors if provided otherwise the ones found in running config

        Args:
            device ('obj'): device under test
            bgp_as ('int'): router bgp_as to configure on
            address_family ('str'): address_family to configure under
            vrf ('str'): vrf to configure under
            neighbors ('list'): List of neighbors to shut/enable
            noshut ('bool'): does the opposite of shut if True
        Returns:        
            N/A
        Raises:
            SubCommandFailure: Failed executing configure commands
            ValueError: Some information is missing

    """
    search = None
    if noshut:
        if neighbors:
            log.info("Enabling router bgp neighbors {}".format(neighbors))
        elif address_family and vrf:
            log.info(
                "Enabling router bgp neighbors under address_family {} and vrf {}"
                .format(address_family, vrf))
            search = "address-family {} vrf {}".format(address_family, vrf)
        elif address_family:
            log.info(
                "Enabling router bgp neighbors under address_family {}".format(
                    address_family))
            search = "address-family {}".format(address_family)
    else:
        if neighbors:
            log.info("Shutting down router bgp neighbors {}".format(neighbors))
        elif address_family and vrf:
            log.info(
                "Shutting down router bgp neighbors under address_family {} and vrf {}"
                .format(address_family, vrf))
            search = "address-family {} vrf {}".format(address_family, vrf)
        elif address_family:
            log.info(
                "Shutting down router bgp neighbors under address_family {}".
                format(address_family))
            search = "address-family {}".format(address_family)

    p1_active_neighbor = re.compile(
        r"^neighbor +(?P<neighbor>[\d\.]+) +activate")
    p2_shutdown_neighbor = re.compile(
        r"^neighbor +(?P<neighbor>[\d\.]+) +shutdown")
    p3_neighbor = re.compile(r"^neighbor +(?P<neighbor>[\d\.]+)")
    cmd = "router bgp {}\n".format(bgp_as)

    if neighbors:
        if noshut:
            for neighbor in neighbors:
                cmd += "no neighbor {} shutdown".format(neighbor)
        else:
            for neighbor in neighbors:
                cmd += "neighbor {} shutdown".format(neighbor)
        try:
            device.configure(cmd)
        except SubCommandFailure:
            if noshut:
                raise SubCommandFailure("Could not enable bgp neighbors")
            else:
                raise SubCommandFailure("Could not shut bgp neighbors")

    else:
        already_shut = []
        config_dict = get_running_config_section_dict(device, "router bgp")
        if config_dict:
            for sub_level in config_dict.get("router bgp {}".format(bgp_as),
                                             {}):

                # Following if/else block is used for neighbors under 'router bgp id' level
                if noshut:
                    m = p2_shutdown_neighbor.match(sub_level)
                    if m:
                        cmd += "no neighbor {} shutdown\n".format(
                            m.groupdict()["neighbor"])
                else:
                    m = p3_neighbor.match(sub_level)
                    if m:
                        if m.groupdict()["neighbor"] not in already_shut:
                            already_shut.append(m.groupdict()["neighbor"])
                            cmd += "neighbor {} shutdown\n".format(
                                m.groupdict()["neighbor"])

                # Following if block is used for neighbors under address_family level
                if search and search in sub_level:

                    # enter address-family
                    cmd += sub_level + "\n"

                    # shut / no shut neighbor
                    for command in config_dict["router bgp {}".format(
                            bgp_as)][sub_level]:
                        if noshut:
                            m = p2_shutdown_neighbor.match(command)
                            if m:
                                cmd += "no neighbor {} shutdown\n".format(
                                    m.groupdict()["neighbor"])
                        else:
                            m = p1_active_neighbor.match(command)
                            if m:
                                cmd += "neighbor {} shutdown\n".format(
                                    m.groupdict()["neighbor"])

                    # exit address-family
                    cmd += "exit-address-family\n"

            if "neighbor" in cmd:
                try:
                    device.configure(cmd)
                except SubCommandFailure:
                    if noshut:
                        raise SubCommandFailure(
                            "Could not enable bgp neighbors")
                    else:
                        raise SubCommandFailure("Could not shut bgp neighbors")

            else:
                if vrf:
                    raise ValueError(
                        "No neighbors found in running config "
                        "under {} address_family and {} vrf.".format(
                            address_family, vrf))
                else:
                    raise ValueError(
                        "No neighbors found in running config "
                        "under {} address_family.".format(address_family))
        else:
            raise ValueError("No running configuration under router bgp.")