Пример #1
0
def verify_bfd_counters(dut,**kwargs):
    """
    Author:[email protected]
    :param peeraddress:
    :type bfd-peer-address
    :param localaddr:
    :type bfd-local-address
    :param interface:
    :type interface
    :param cntrlpktOut:
    :type control-packet-out
    :param cntrlpktIn:
    :type control-acket-in
    :param echopktin:
    :type echo-packet-in
    :param echopktout:
    :type echo-packet-out
    :param sessionupev:
    :type session-up-event
    :param sessiondownev:
    :type session-down-event
    :param zebranotifys:
    :type Zebra-notifications
    :param dut:
    :type dut:
    :return:
    :rtype:

    usage:
    bfd.verify_bfd_counters(dut1,cntrlpktout="100",cntrlpktin="100",peeraddress="5000::2")
    bfd.verify_bfd_counters(dut1,cntrlpktout="200",cntrlpktin="200",peeraddress="50.1.1.2")
    """
    cli_type = st.get_ui_type(dut, **kwargs)

    result = False
    st.log("verify show bfd peers counters")

    if 'vrf_name' in kwargs:
        vrf = kwargs['vrf_name']
        if vrf == 'default':
            vrf = 'default-vrf'
        del kwargs['vrf_name']
    else:
        vrf = 'default-vrf'

    cmd = "show bfd"
    if vrf != 'default-vrf':
        if cli_type == 'click':
            cmd = cmd + ' vrf ' + vrf + ' peers counters'
        elif cli_type == 'klish':
            cmd = cmd + ' peers' + ' vrf ' + vrf +' counters'
    else:
        cmd = cmd + ' peers counters'

    output = []
    if cli_type in ['click', 'klish']:
        cli_type = "vtysh" if cli_type == "click" else cli_type
        output = st.show(dut, cmd, type=cli_type)
    elif cli_type in ['rest-patch', 'rest-put']:
        # st.show(dut, "show bfd peers counters", type='klish')
        output = rest_get_bfd_peer_info(dut, 'counters')
    else:
        st.error("Invalid UI-Type: {} provided".format(cli_type))
        return False

    if len(output) == 0:
        st.error("OUTPUT is Empty")
        return False

    match_dict = {}
    if 'peeraddress' in kwargs:
        match_dict['peeraddress'] = kwargs['peeraddress']
    else:
        st.error("Mandatory parameter peeraddress is not found")
        return result

    out_param = []
    for key in kwargs:
        out_param.append(key)
    entries = filter_and_select(output,out_param, match_dict)

    if bool(entries):
        if 'cntrlpktout' in out_param:
            if int(entries[0]['cntrlpktout']) >= int(kwargs['cntrlpktout']):
                result = True
                st.log("Number of output BFD Control packet is {} for peer {} Test Passed".format(int(entries[0]['cntrlpktout']),kwargs['peeraddress']))
            else:
                result = False
                st.error("Number of output BFD Control packet is {} for peer {} Test Failed as less than expected".format(int(entries[0]['cntrlpktout']),kwargs['peeraddress']))
        if 'cntrlpktin' in out_param:
            if int(entries[0]['cntrlpktin']) >= int(kwargs['cntrlpktin']):
                result = True
                st.log("Number of input BFD Control packet is {} for peer {} Test Passed".format(int(entries[0]['cntrlpktin']),kwargs['peeraddress']))
            else:
                result = False
                st.error("Number of input BFD Control packet is {} for peer {} Test Failed as less than expected".format(int(entries[0]['cntrlpktin']),kwargs['peeraddress']))
        if 'cntrlpktout' not in out_param and 'cntrlpktin' not in out_param:
            result = True
            st.log("BFD Peer IP {} exist in the output - Test Passed".format(kwargs['peeraddress']))
        if 'SessionUpEv' in out_param:
            if int(entries[0]['SessionUpEv']) == int(kwargs['SessionUpEv']):
                result = True
                st.log("Number of BFD UP event is {} for peer {} Test Passed".format(int(entries[0]['SessionUpEv']), kwargs['peeraddress']))
            else:
                result = False
                st.log("Number of BFD UP event is {} for peer {} Test Failed".format(int(entries[0]['SessionUpEv']), kwargs['peeraddress']))
        if 'SessionDownEv' in out_param:
            if int(entries[0]['SessionDownEv']) == int(kwargs['SessionDownEv']):
                result = True
                st.log("Number of BFD Down event is {} for peer {} Test Passed".format(int(entries[0]['SessionDownEv']), kwargs['peeraddress']))
            else:
                result = False
                st.log("Number of BFD Down event is {} for peer {} Test Failed".format(int(entries[0]['SessionDownEv']), kwargs['peeraddress']))
    else:
        st.error("Either BFD Peer IP {} or other passed arguments does not exist".format(kwargs['peeraddress']))

    return result
Пример #2
0
def config_global_server_params(dut,
                                skip_error_check=False,
                                params=dict(),
                                cli_type=""):
    """
    Config / Unconfig global server params using provided parameters
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :param params: {"source_ip":{"value":"10.20.3.1", "no_form": False}, "key":{"value":"ABCD", "no_form": True},
                "auth_port":{"value":"56", "no_form": False}, "timeout":{"value":"30", "no_form": True}}
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    st.log("Configuring GLOBAL SERVER Parameters ...")
    if not params:
        st.log("Invalid parameters provided ..")
        return False
    count = 0
    if cli_type == "klish":
        cmd = "radius-server"
        fields = {
            "source_ip": "source-ip",
            "key": "key",
            "auth_type": "auth-type",
            "timeout": "timeout",
            "retransmit": "retransmit",
            "nasip": "nas-ip",
            "statistics": "statistics"
        }
        for key, value in params.items():
            if value.get("no_form"):
                command = "no {} {}".format(cmd, fields[key])
            else:
                command = "{} {} {}".format(cmd, fields[key], value["value"])
            output = st.config(dut,
                               command,
                               type=cli_type,
                               skip_error_check=skip_error_check)
            if "% Error" in utils.remove_last_line_from_string(output):
                st.log(utils.remove_last_line_from_string(output))
                return False
            count += 1
    elif cli_type == "click":
        cmd = "config radius"
        fields = {
            "source_ip": "sourceip",
            "key": "passkey",
            "auth_type": "authtype",
            "timeout": "timeout",
            "retransmit": "retransmit",
            "nasip": "nasip",
            "statistics": "statistics"
        }
        for key, value in params.items():
            if value.get("no_form"):
                if key == "source_ip":
                    command = "{} default {} {}".format(
                        cmd, fields[key], value["value"])
                else:
                    command = "{} default {}".format(cmd, fields[key])
            else:
                command = "{} {} {}".format(cmd, fields[key], value["value"])
            output = st.config(dut,
                               command,
                               type=cli_type,
                               skip_error_check=skip_error_check)
            if "Valid chars are" in utils.remove_last_line_from_string(output):
                st.log(utils.remove_last_line_from_string(output))
                return False
            count += 1
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url_mapping = {
            "source_ip": "radius_sourceip",
            "key": "radius_key",
            "auth_type": "radius_authtype",
            "timeout": "radius_timeout",
            "retransmit": "radius_retransmit",
            "nasip": "radius_nasip",
            "statistics": "radius_statistics"
        }
        for key, value in params.items():
            if value.get("no_form"):
                url = rest_urls[url_mapping[key]].format("RADIUS")
                if not delete_rest(dut, rest_url=url, timeout=time_out):
                    return False
            else:
                url = rest_urls['aaa_server_config']
                if key == "statistics":
                    data = {
                        "openconfig-system:server-group": [{
                            "name": "RADIUS",
                            "config": {
                                "name": "RADIUS"
                            },
                            "openconfig-aaa-radius-ext:radius": {
                                "config": {
                                    "statistics": True
                                }
                            }
                        }]
                    }
                elif key == 'nasip':
                    data = {
                        "openconfig-system:server-group": [{
                            "name": "RADIUS",
                            "config": {
                                "name": "RADIUS"
                            },
                            "openconfig-aaa-radius-ext:radius": {
                                "config": {
                                    "nas-ip-address": value["value"]
                                }
                            }
                        }]
                    }
                elif key == 'retransmit':
                    data = {
                        "openconfig-system:server-group": [{
                            "name": "RADIUS",
                            "openconfig-aaa-radius-ext:radius": {
                                "config": {
                                    "retransmit-attempts": int(value["value"])
                                }
                            }
                        }]
                    }
                elif key == 'timeout':
                    data = {
                        "openconfig-system:server-group": [{
                            "name": "RADIUS",
                            "config": {
                                "name":
                                "RADIUS",
                                "openconfig-system-ext:timeout":
                                int(value["value"])
                            }
                        }]
                    }
                elif key == 'auth_type':
                    data = {
                        "openconfig-system:server-group": [{
                            "name": "RADIUS",
                            "config": {
                                "name": "RADIUS",
                                "openconfig-system-ext:auth-type":
                                value["value"]
                            }
                        }]
                    }
                elif key == 'key':
                    data = {
                        "openconfig-system:server-group": [{
                            "name": "RADIUS",
                            "config": {
                                "name": "RADIUS",
                                "openconfig-system-ext:secret-key":
                                value["value"]
                            }
                        }]
                    }
                elif key == 'source_ip':
                    data = {
                        "openconfig-system:server-group": [{
                            "name": "RADIUS",
                            "config": {
                                "name":
                                "RADIUS",
                                "openconfig-system-ext:source-address":
                                value["value"]
                            }
                        }]
                    }
                else:
                    continue
                if not config_rest(dut,
                                   http_method=cli_type,
                                   rest_url=url,
                                   json_data=data,
                                   timeout=time_out):
                    return False
                count += 1
    else:
        st.error("UNSUPPORTED CLI_TYPE: {}".format(cli_type))
        return False
    if count > 0:
        return True
    st.log(
        "Returning False as the command execution is not happened with the provided parameters .. "
    )
    return False
Пример #3
0
def verify_config(dut, params, cli_type=""):
    """
    API to verify the Radius Parameters
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :param params: {"globals":{"global_auth_type":"pap", "global_source_ip":'10.25.36.25'},
    "servers":[{'auth_port': '1815', 'priority': '1', 'address': '1.1.1.5'},
      {'auth_port': '1812', 'priority': '1', 'address': '1.1.1.1'}]}
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if not isinstance(params, dict):
        st.log("Unsupported data format provided...")
        return False

    output = show_config(dut, cli_type=cli_type)
    if not output:
        st.log("Identified empty radius output ..")
        return False
    if "globals" in params and params["globals"]:
        for key, value in params["globals"].items():
            if str(value) != str(output["globals"][0][key]):
                st.log(
                    "Verification of radius global parameters {} with {} values is failed"
                    .format(key, value))
                return False
    if "servers" in params and params["servers"]:
        for details in params["servers"]:
            is_found = 0
            for data in output["servers"]:
                for key, value in details.items():
                    if str(value) != str(data[key]):
                        st.log("Verifications of {} with {} values is failed".
                               format(key, value))
                        is_found = 0
                    else:
                        st.log("Radius server Key Value verification success")
                        is_found += 1
                if is_found == len(details):
                    st.log("Already found, hence breaking the iteration ..")
                    break
            if is_found != len(details):
                st.log(
                    "Verification of radius server parameter verification failed.."
                )
                return False
    if "globals" in params and params[
            "globals"] or "servers" in params and params["servers"]:
        st.log("Verification of radius server parameters SUCCESS ..")
        return True
Пример #4
0
def config_tc_to_dscp_map(dut, obj_name, tc_to_dscp_map_dict, **kwargs):
    """
    Author: Jagadish Chatrasi ([email protected])
    To map the tc to dscp
    :param dut:
    :type dut:
    :param obj_name:
    :type obj_name:
    :param tc_to_dscp_map_dict:
    :type dict:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type == 'click':
        final_data = dict()
        temp_data = dict()
        tc_to_dscp_map_dict = get_non_range_map_data_from_range_map_data(
            tc_to_dscp_map_dict)
        if not tc_to_dscp_map_dict or not obj_name:
            st.log(
                "Please provide traffic class to dscp map dict. For example - {'0':'0', '1':'1', ...} and Object name like 'AZURE'"
            )
            return False
        else:
            temp_data[obj_name] = tc_to_dscp_map_dict
        final_data['TC_TO_DSCP_MAP'] = temp_data
        final_data = json.dumps(final_data)
        st.apply_json(dut, final_data)
    elif cli_type == 'klish':
        commands = list()
        commands.append('qos map tc-dscp {}'.format(obj_name))
        for tc, dscp in tc_to_dscp_map_dict.items():
            commands.append('traffic-class {} dscp {}'.format(tc, dscp))
        commands.append('exit')
        response = st.config(dut, commands, type=cli_type)
        if any(error in response.lower() for error in errors_list):
            st.error("The response is: {}".format(response))
            return False
    elif cli_type in ['rest-patch', 'rest-put']:
        cli_type = 'rest-patch'
        rest_urls = st.get_datastore(dut, 'rest_urls')
        url = rest_urls['tc_dscp_map_config'].format(obj_name)
        tc_to_dscp_map_dict = get_non_range_map_data_from_range_map_data(
            tc_to_dscp_map_dict)
        maps_data = [{
            "fwd-group": str(tc),
            "config": {
                "fwd-group": str(tc),
                "dscp": int(dscp)
            }
        } for tc, dscp in tc_to_dscp_map_dict.items()]
        tc_dscp_map_data = {
            "openconfig-qos-maps-ext:forwarding-group-dscp-map": [{
                "name": obj_name,
                "config": {
                    "name": obj_name
                },
                "forwarding-group-dscp-map-entries": {
                    "forwarding-group-dscp-map-entry": maps_data
                }
            }]
        }
        if not config_rest(dut,
                           rest_url=url,
                           http_method=cli_type,
                           json_data=tc_dscp_map_data):
            st.error("Failed to map TC to DSCP with data: {}".format(
                tc_to_dscp_map_dict))
            return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True
Пример #5
0
def dhcp_relay_config(dut, **kwargs):
    """
    API for DHCP relay configuration
    Author Chaitanya Vella ([email protected])
    :param dut:
    :param kwargs:
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    interface = kwargs.get("vlan", kwargs.get("interface", None))
    ip_address = make_list(kwargs.get('IP', []))
    ip_addr_lst = " ".join(ip_address)
    ip_family = kwargs.get("family", "ipv4")
    skip_error_check = kwargs.get("skip_error_check", False)
    action = kwargs.get("action","add")
    if not interface:
        st.error("Required key 'interface' is not passed")
        return False
    command = ""
    if cli_type == "click":
        if ip_family == "ipv4":
            command = "config interface ip dhcp-relay {} {} {}".format(action, interface, ip_addr_lst)
        else:
            command = "config interface ipv6 dhcp-relay {} {} {}".format(action, interface, ip_addr_lst)
        if 'link_select' in kwargs:
            link_select = 'enable'
            command += " -link-select={}".format(link_select)
        if 'src_interface' in kwargs:
            src_interface = kwargs['src_interface']
            command += " -src-intf={}".format(src_interface)
        if 'max_hop_count' in kwargs:
            max_hop_count = kwargs['max_hop_count']
            command += " -max-hop-count={}".format(max_hop_count)
        if 'vrf_name' in kwargs and action == 'add':
            vrf_name = kwargs['vrf_name']
            command += " -vrf-name={}".format(vrf_name)
        if 'vrf_select' in kwargs:
            vrf_select = kwargs['vrf_select']
            command += " -vrf-select={}".format(vrf_select)
    elif cli_type == "klish":
        if ip_family not in ["ipv4", "ipv6"]:
            st.error("INVALID IP FAMILY -- {}".format(ip_family))
            return False
        command = list()
        interface_data = get_interface_number_from_name(interface)
        command.append("interface {} {}".format(interface_data.get("type"), interface_data.get("number")))
        no_form = "" if action == "add" else "no"
        ip_string = "ip" if ip_family == "ipv4" else "ipv6"
        if kwargs.get("link_select") and not kwargs.get("src_interface"):
            st.log("SRC INTF needed for LINK SELECT operation")
            return False
        if ip_addr_lst:
            cmd = "{} {} dhcp-relay {}".format(no_form, ip_string, ip_addr_lst)
            if 'vrf_name' in kwargs and action == 'add':
                cmd += " vrf-name {}".format(kwargs['vrf_name'])
            command.append(cmd)
        if 'src_interface' in kwargs:
            src_interface = kwargs['src_interface']
            command.append("{} {} dhcp-relay source-interface {}".format(no_form, ip_string, src_interface))
        if 'link_select' in kwargs:
            command.append("{} {} dhcp-relay link-select".format(no_form, ip_string))
        if 'max_hop_count' in kwargs:
            max_hop_count = kwargs['max_hop_count']
            command.append("{} {} dhcp-relay max-hop-count {}".format(no_form, ip_string, max_hop_count))
        if 'vrf_select' in kwargs:
            vrf_select = kwargs['vrf_select']
            command.append("{} {} dhcp-relay vrf-select {}".format(no_form, ip_string, vrf_select))
    elif cli_type in ["rest-patch", "rest-put"]:
        if ip_family not in ["ipv4", "ipv6"]:
            st.error("INVALID IP FAMILY -- {}".format(ip_family))
            return False
        ip_string = "" if ip_family == "ipv4" else "v6"
        if kwargs.get("link_select") and not kwargs.get("src_interface"):
            st.log("SRC INTF needed for LINK SELECT operation")
            return False
        config_data = {"openconfig-relay-agent:config": {"id": interface}}
        rest_urls = st.get_datastore(dut, 'rest_urls')
        if ip_address:
            if action == 'add':
                config_data["openconfig-relay-agent:config"].update({"helper-address": ip_address})
                if kwargs.get('vrf_name'):
                    config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:vrf": kwargs['vrf_name']})
            else:
                for ip in ip_address:
                    if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_address_config'.format(ip_string)].format(id=interface, helper_address=ip)):
                        st.error("Failed to delete DHCP-Relay Helper-Address: {}".format(ip))
                        return False
        if 'src_interface' in kwargs:
            if action == 'add':
                config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:src-intf": kwargs['src_interface']})
            else:
                if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_src_intf_config'.format(ip_string)].format(id=interface)):
                    st.error("Failed to delete DHCP-Relay source-interface on interface: {}".format(interface))
                    return False
        if 'link_select' in kwargs:
            if action == 'add':
                config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:link-select": "ENABLE"})
            else:
                if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_link_select_config'.format(ip_string)].format(id=interface)):
                    st.error("Failed to delete DHCP-Relay link-select")
                    return False
        if 'max_hop_count' in kwargs:
            if action == 'add':
                config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:max-hop-count": int(kwargs['max_hop_count'])})
            else:
                if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_max_hop_count_config'.format(ip_string)].format(id=interface)):
                    st.error("Failed to delete DHCP-Relay max-hop-count on interface: {}".format(interface))
                    return False
        if 'vrf_select' in kwargs:
            if action == 'add':
                config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:vrf-select": "ENABLE"})
            else:
                if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_vrf_select_config'.format(ip_string)].format(id=interface)):
                    st.error("Failed to delete DHCP-Relay vrf-select on interface: {}".format(interface))
                    return False
        if 'policy_action' in kwargs:
            if action == 'add':
                config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:policy-action": kwargs['policy_action'].upper()})
            else:
                if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_policy_action_config'.format(ip_string)].format(id=interface)):
                    st.error("Failed to delete DHCP-Relay policy_action on interface: {}".format(interface))
                    return False
        if len(config_data["openconfig-relay-agent:config"]) > 1:
            if not config_rest(dut, rest_url=rest_urls['dhcp{}_relay_config'.format(ip_string)].format(id=interface), http_method=cli_type, json_data=config_data):
                st.error("Failed to configure DHCP-Relay parameters")
                return False
    else:
        st.error("Unsupported CLI_TYPE: {}".format(cli_type))
        return False
    if command:
        st.debug("command is {}".format(command))
        output = st.config(dut, command, skip_error_check=skip_error_check, type=cli_type)
        if "Error" in output:
            if skip_error_check:
                return True
            else:
                return False
    return True
Пример #6
0
def log_info(fmt, *args):
    st.log(fmt % args)
Пример #7
0
def config_dot1p_to_tc_map(dut, obj_name, dot1p_to_tc_map_dict, **kwargs):
    """
    Author: Jagadish Chatrasi ([email protected])
    To map the dot1p to tc
    :param dut:
    :type dut:
    :param obj_name:
    :type obj_name:
    :param dot1p_to_tc_map_dict:
    :type dict:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type == 'click':
        final_data = dict()
        temp_data = dict()
        dot1p_to_tc_map_dict = get_non_range_map_data_from_range_map_data(
            dot1p_to_tc_map_dict)
        if not dot1p_to_tc_map_dict or not obj_name:
            st.log(
                "Please provide dot1p value to traffic class value map dict. For example - {'0':'0', '1':'1', ...} and Object name like 'AZURE'"
            )
            return False
        else:
            temp_data[obj_name] = dot1p_to_tc_map_dict
        final_data['DOT1P_TO_TC_MAP'] = temp_data
        final_data = json.dumps(final_data)
        st.apply_json(dut, final_data)
    elif cli_type == 'klish':
        commands = list()
        commands.append('qos map dot1p-tc {}'.format(obj_name))
        for dot1p, tc in dot1p_to_tc_map_dict.items():
            commands.append('dot1p {} traffic-class {}'.format(dot1p, tc))
        commands.append('exit')
        response = st.config(dut, commands, type=cli_type)
        if any(error in response.lower() for error in errors_list):
            st.error("The response is: {}".format(response))
            return False
    elif cli_type in ['rest-patch', 'rest-put']:
        cli_type = 'rest-patch'
        rest_urls = st.get_datastore(dut, 'rest_urls')
        url = rest_urls['dot1p_tc_map_config'].format(obj_name)
        dot1p_to_tc_map_dict = get_non_range_map_data_from_range_map_data(
            dot1p_to_tc_map_dict)
        maps_data = [{
            "dot1p": int(dot1p),
            "config": {
                "dot1p": int(dot1p),
                "fwd-group": str(tc)
            }
        } for dot1p, tc in dot1p_to_tc_map_dict.items()]
        dot1p_tc_map_data = {
            "openconfig-qos-maps-ext:dot1p-map": [{
                "name": obj_name,
                "config": {
                    "name": obj_name
                },
                "dot1p-map-entries": {
                    "dot1p-map-entry": maps_data
                }
            }]
        }
        if not config_rest(dut,
                           rest_url=url,
                           http_method=cli_type,
                           json_data=dot1p_tc_map_data):
            st.error("Failed to map DOT1P to TC with data: {}".format(
                dot1p_to_tc_map_dict))
            return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True
Пример #8
0
def arp_static_route_reboot_module_hooks(request):
    # add things at the start of this module
    init_vars()
    initialize_variables()
    get_parms()

    global tg_handler
    tg_handler = tgapi.get_handles_byname("T1D1P1", "T1D1P2")
    global tg
    tg = tg_handler["tg"]
    st.log("configuring static route")
    adding_static_route()
    st.log("Getting ARP entry dynamically")
    adding_dynamic_arp()
    ip_obj.config_ip_addr_interface(vars.D1,
                                    vars.D1T1P2,
                                    data.ipv4_address_1,
                                    data.mask,
                                    family="ipv4",
                                    config='add')
    st.log("Configuring static ARP")
    arp_obj.add_static_arp(vars.D1, data.static_arp_ip, data.static_arp_mac,
                           vars.D1T1P2)
    st.log(
        "Verifying static route entries before save and reboot/fast-reboot/warm-reboot"
    )
    static_route_verify()
    st.log(
        "Verifying dynamic ARP entries before save and reboot/fast-reboot/warm-reboot"
    )
    if not arp_obj.verify_arp(vars.D1, data.ipv4_address_tgen,
                              data.src_mac_addr, vars.D1T1P1):
        st.report_fail("ARP_entry_dynamic_entry_fail", data.ipv4_address_tgen,
                       vars.D1)
    else:
        st.log("Verified that dynamic ARP entry is present in arp table")
    st.log(
        "Verifying static ARP entries before save and reboot/fast-reboot/warm-reboot"
    )
    if not arp_obj.verify_arp(vars.D1, data.static_arp_ip, data.static_arp_mac,
                              ""):
        st.report_fail("static_arp_create_fail", vars.D1)
    else:
        st.log("Verified that static ARP entry is present in arp table")
    st.log("Save the config on the DUT")
    rb_obj.config_save(vars.D1)
    st.log("saving config in vtysh mode to save static route")
    rb_obj.config_save(vars.D1, shell="vtysh")
    yield
    # Below step will clear IP adresses configured on different interfaces in the device
    ip_obj.clear_ip_configuration(st.get_dut_names())
    #Below step will clear static route configured in the device
    ip_obj.delete_static_route(vars.D1,
                               data.ipv4_address_tgen,
                               data.ipv4_address_network,
                               family='ipv4',
                               shell="vtysh")
    #Below step will delete static arp entries configured in the device
    arp_obj.delete_static_arp(vars.D1, data.static_arp_ip, vars.D1T1P2)
Пример #9
0
def test_ft_ztp_config_section_check_with_inband_and_option_67(ztp_func_hooks):
    # ################ Author Details ################
    # Name: Chaitanya Vella
    # Email: [email protected]
    # ################################################
    # ############## Test bed details ################
    #  D1 ---- DHCP Server
    #  ft_ztp_config_section_check_with_option_67_with_inband	:
    #  Verify that SONiC ZTP is successful through in-band ports using
    #  ZTP URL provided in DHCP option 67 received over IPv4 network.
    # #################################################
    vars = st.ensure_min_topology("D1")
    hostname = basic_obj.get_hostname(vars.D1)
    config_params.config_file = "ztp_option_67_with_inband.json"
    config_params.static_ip = ztp_params.dhcp.inband_static_ip if not ztp_params.port else "{}:{}".format(ztp_params.dhcp.inband_static_ip, ztp_params.port)
    config_params.config_path = ztp_params.config_path
    config_params.dhcp_config_file = ztp_params.dhcp.inband_config_file
    config_params.type = "http"
    config_params.dhcp_service_name = data.dhcp_service_name
    config_params.action = 'restart'
    config_params.device = 'server'
    config_params.device_action = "reboot"
    config_params.reboot_type = "normal"
    config_params.ztp_log_path = data.ztp_log_path
    config_params.file_names = ["03-provisioning-script", "05-test-plugin", "06-snmp", "07-configdb-json"]
    config_params.log_msg = "Checking configuration section {} result: SUCCESS"
    config_params.ztp_log_string = "ZTP successfully completed"
    config_params.option_type = "67"
    config_params.result = ""
    config_params.service = "disable"
    config_params.config_db_path = data.config_db_path
    config_params.config_db_location = "json"
    config_params.config_db_temp = data.config_db_temp
    config_params.config_db_file_name = "{}_config_db.json".format(hostname)
    config_params.featureconfig_file_name = "feature_config.json"
    config_params.json_config_path = "http://{}{}/".format(config_params.static_ip, ztp_params.config_path)
    config_params.provision_script_path = "http://{}{}/{}".format(config_params.static_ip,
                                                                  ztp_params.provision_script_path,
                                                                  data.option_239_sh_file)
    config_params.config_db_url = "http://{}{}/{}".format(config_params.static_ip,
                                                          ztp_params.config_path, config_params.config_db_file_name)
    data.feature_config_url = "http://{}{}/{}".format(config_params.static_ip, ztp_params.config_path,
                                                      config_params.featureconfig_file_name)
    config_params.band_type="inband"
    config_params.json_content = {
        "ztp": {
            # "02-configdb-json": {
            #     "dynamic-url": {
            #         "source": {
            #             "prefix": config_params.json_config_path,
            #             "identifier": "hostname",
            #             "suffix": "_config_db.json"
            #         },
            #         "destination": "/etc/sonic/config_db.json"
            #     }
            # },
            "03-provisioning-script": {
                "plugin": {
                    "url": config_params.provision_script_path
                }
            },
            "05-test-plugin":{
                "message": "Test-Plugin-Test",
                "message-file": "/home/admin/test-file1"
            },
            "06-snmp": {
                "communities-ro": ["sonic", "buzznik"],
                "community-ro": "sonicro",
                "snmp-location": "Hyderabad",
                "snmp-syscontact": "admin",
                "ignore-result": "true",
                "restart-agent": True
            },
            "07-configdb-json": {"url":
                             {"source": data.feature_config_url, "timeout": 300},
                             "clear-config": "false", "save-config": "true", "ignore-result": True}
        }
    }
    ztp_obj.config_ztp_backdoor_options(vars.D1, ztp_cfg={"admin-mode": True, "restart-ztp-interval": 30, "log-level":"DEBUG", "feat-console-logging": feat_logging_console})
    source_path = "{}{}".format(data.local_provision_scripts_folder, data.option_239_sh_file)
    destination_path = "{}{}/{}".format(ztp_params.home_path, ztp_params.provision_script_path, data.option_239_sh_file)
    basic_obj.copy_file_from_client_to_server(ssh_conn_obj, src_path=source_path, dst_path=destination_path,
                                              persist=True)

    options = SpyTestDict()
    options.dhcp_config_file = ztp_params.dhcp.inband_config_file
    options.server_ip = config_params.static_ip
    options.config_path = ztp_params.provision_script_path
    options.provision_script = data.option_239_sh_file
    options.search_pattern = r'\s*option\s+provision-url\s*\S*\s*"\S+";'
    options.option_string = 'option provision-url '
    options.option_url = "http://{}{}/{}".format(ztp_params.dhcp.inband_static_ip, ztp_params.provision_script_path,
                                                 data.option_239_sh_file)
    ztp_obj.write_option_to_dhcp_server(ssh_conn_obj, options)
    # ztp_obj.write_option_239_to_dhcp_server(ssh_conn_obj, options)
    shell_scripts = [data.option_239_sh_file]
    for shell_script in shell_scripts:
        source_path = "{}{}".format(data.local_provision_scripts_folder, shell_script)
        destination_path = "{}{}/{}".format(ztp_params.home_path, ztp_params.provision_script_path, shell_script)
        basic_obj.copy_file_from_client_to_server(ssh_conn_obj, src_path=source_path, dst_path=destination_path,
                                                  persist=True)
    st.log("Preparing invalid config JSON to check the gracefull handling of ZTP ...")
    interface_name = random.choice(st.get_free_ports(vars.D1))
    vlan_list = vlan_obj.get_non_existing_vlan(vars.D1, 1)
    data.config_db_content = {
        "VLAN": {"Vlan{}".format(vlan_list[0]): {"members": [interface_name], "vlanid": vlan_list[0]}},
        "VLAN_MEMBER": {"Vlan{}|{}".format(vlan_list[0], interface_name): {"tagging_mode": "tagged"}}}
    file_path = basic_obj.write_to_json_file(data.config_db_content)
    destination_path = "{}{}/{}".format(ztp_params.home_path, ztp_params.config_path, config_params.featureconfig_file_name)
    basic_obj.copy_file_from_client_to_server(ssh_conn_obj, src_path=file_path, dst_path=destination_path)
    ztp_obj.config_and_verify_dhcp_option(ssh_conn_obj, vars.D1, ztp_params, config_params)
    # if ztp_params.cli_type == "click":
    #     st.log("Verifying the ZTP DEBUG logs ..")
    #     ztp_log_string = "DEBUG sonic-ztp"
    #     st.log(st.log(ztp_log_string))
    #     if not basic_obj.poll_for_error_logs(vars.D1, data.ztp_log_path, ztp_log_string):
    #         if not basic_obj.poll_for_error_logs(vars.D1, data.syslog_path, ztp_log_string):
    #             st.log("ZTP log {} verification failed for message {}".format(data.ztp_log_path, ztp_log_string))
    #             st.report_fail("ztp_log_verification_failed", data.ztp_log_path, ztp_log_string)
    ztp_status = ztp_obj.show_ztp_status(vars.D1)
    if "dhcp-opt67" not in ztp_status["source"]:
        st.log("ZTP source verification failed with {} against dhcp-opt239".format(ztp_status["source"]))
        st.report_fail("ztp_source_verification_failed", "dhcp-opt239", ztp_status["source"])
    st.log("Verifying the ZTP plugin chronological order ..")
    if not ztp_obj.verify_plugin_chronological_order(vars.D1):
        st.report_fail("ztp_chronoloigical_verification_failed")
    st.log("Verifying ZTP admin disable operation ..")
    ztp_status = ztp_obj.show_ztp_status(vars.D1)
    ztp_obj.ztp_operations(vars.D1, "disable")
    if not ztp_obj.verify_ztp_attributes(vars.D1, "adminmode", "False"):
        st.log("ZTP status verification failed")
        st.report_fail("ztp_status_verification_failed")
    ztp_status_after_disable = ztp_obj.show_ztp_status(vars.D1)
    if ztp_status["status"] != ztp_status_after_disable["status"]:
        st.log("ZTP status verification failed")
        st.report_fail("ztp_status_verification_failed")
    snmp_params = {"rocommunityv6": "sonic", "rocommunity": "sonic"}
    if not verify_snmp_details_using_docker(vars.D1, **snmp_params):
        st.report_fail("snmp_params_verification_failed")
    snmp_params = {"rocommunityv6": "buzznik", "rocommunity": "buzznik"}
    if not verify_snmp_details_using_docker(vars.D1, **snmp_params):
        st.report_fail("snmp_params_verification_failed")
    snmp_params = {"syslocation": "Hyderabad"}
    if not verify_snmp_details_using_docker(vars.D1, **snmp_params):
        st.report_fail("snmp_params_verification_failed")
    snmp_params = {"syscontact": "admin"}
    if not verify_snmp_details_using_docker(vars.D1, **snmp_params):
        st.report_fail("snmp_params_verification_failed")
    st.report_pass("test_case_passed")
Пример #10
0
def rest_get_bfd_peer_info(dut, type, bfd_type=None, peer_list=True, **kwargs):
    """
    Author: Lakshminarayana D([email protected])
    :param dut:
    :type bfd_type: None, single, multi
    :param type: brief, counters, peers
    :param peer_list: True: get all peer info, False: get particular peer info
    :return:
    """

    rest_urls = st.get_datastore(dut, "rest_urls")
    bfd_peer_state=[]
    if peer_list:
        if not bfd_type:
            uri = rest_urls['config_bfd_peer_list']
            result = get_rest(dut, rest_url=uri)
            if not result: return []
            if result['output']['openconfig-bfd:bfd'].get('openconfig-bfd-ext:bfd-shop-sessions', ''):
                shop_state = result['output']['openconfig-bfd:bfd']['openconfig-bfd-ext:bfd-shop-sessions'].get('single-hop', '')
                if shop_state: bfd_peer_state.extend(shop_state)
            if result['output']['openconfig-bfd:bfd'].get('openconfig-bfd-ext:bfd-mhop-sessions', ''):
                mhop_state = result['output']['openconfig-bfd:bfd']['openconfig-bfd-ext:bfd-mhop-sessions'].get('multi-hop', '')
                if mhop_state: bfd_peer_state.extend(mhop_state)
        elif bfd_type == 'single':
            uri = rest_urls['config_bfd_shop_peer_list']
            result = get_rest(dut, rest_url=uri)
            if not result: return []
            if result['output'].get('openconfig-bfd-ext:single-hop', ''):
                shop_state = result['output'].get('openconfig-bfd-ext:single-hop', '')
                if shop_state: bfd_peer_state.extend(shop_state)
        elif bfd_type == 'multi':
            uri = rest_urls['config_bfd_mhop_peer_list']
            result = get_rest(dut, rest_url=uri)
            if not result: return []
            if result['output'].get('openconfig-bfd-ext:multi-hop', ''):
                mhop_state = result['output'].get('openconfig-bfd-ext:multi-hop', '')
                if mhop_state: bfd_peer_state.extend(mhop_state)
    else:
        if type == 'peers':
            peer_data = dict()
            hop_type = 'shop' if bfd_type == 'single' else 'mhop'
            if not kwargs.get('peer', '') or not kwargs.get('vrf', ''):
                st.error('Mandatory params not provided to perform a rest operation')
                return []

            intf = kwargs['interface'] if kwargs.get('interface', '') else 'null'
            local_addr = kwargs['local_addr'] if kwargs.get('local_addr', '') else 'null'
            peer_data['vrf'] = kwargs.get('vrf', 'default')
            peer_data['remote-address'] = kwargs.get('peer')
            peer_data['interface'] = kwargs.get('interface', '')
            peer_data['local-address'] = kwargs.get('local_addr', '')

            key_map = {'uptime': 'last-up-time', 'downtime': 'last-failure-time', 'local_id': 'local-discriminator',
                        'remote_id': 'remote-discriminator', 'status': 'session-state',
                        'diagnostics': 'local-diagnostic-code',
                        'remote_diagnostics': 'remote-diagnostic-code', 'peer_type': 'session-type',
                        'multiplier_local': 'detection-multiplier', 'multiplier_remote': 'remote-multiplier',
                        'tx_interval_local': 'desired-minimum-tx-interval',
                        'tx_interval_remote': 'remote-desired-transmission-interval',
                        'rx_interval_local': 'required-minimum-receive',
                        'rx_interval_remote': 'remote-minimum-receive-interval',
                        'echo_tx_interval_local': 'desired-minimum-echo-receive',
                        'echo_tx_interval_remote': 'remote-echo-receive-interval'}
            if bfd_type == 'multi':
                key_map.pop('echo_tx_interval_local', '')
                key_map.pop('echo_tx_interval_remote', '')

            peer_data['state'] = dict()
            for key, map in key_map.items():
                cmd = 'get_bfd_peer_state_{}'.format(key)
                uri = rest_urls[cmd].format(hop_type, bfd_type, peer_data['remote-address'], intf, peer_data['vrf'], local_addr)
                result = get_rest(dut, rest_url=uri)
                if result:
                    peer_data['state'][map] = result['output'].get('openconfig-bfd-ext:{}'.format(map), '')
                else:
                    st.error('Rest response failed for uri type: {}'.format(map))
                    peer_data['state'][map] = ''
            bfd_peer_state.append(peer_data)

    if not bfd_peer_state: return []

    bfd_rest_data = []
    for peer_info in bfd_peer_state:
        temp=dict()
        if not peer_info.get('state'): continue
        if type == 'brief':
            temp['scount'] = str(len(bfd_peer_state))
            temp['sessionid'] = peer_info['state'].get('local-discriminator', '')
            temp['ouraddress'] = peer_info.get('local-address') if peer_info.get('local-address') != 'null' else 'unknown'
            temp['peeraddress'] = peer_info.get('remote-address', '')
            temp['status'] = peer_info['state'].get('session-state', '').lower()
            temp['vrf'] = peer_info.get('vrf', '')
            bfd_rest_data.append(temp)
        elif type == 'counters':
            temp['peeraddress'] = peer_info.get('remote-address', '')
            temp['vrfname'] = peer_info.get('vrf', '')
            temp['localaddr'] = peer_info.get('local-address', '')
            temp['interface'] = peer_info.get('interface', '')
            temp['cntrlpktin'] = peer_info['state']['async'].get('received-packets', '')
            temp['cntrlpktout'] = peer_info['state']['async'].get('transmitted-packets', '')
            temp['sessionupev'] = peer_info['state']['async'].get('up-transitions', '')
            temp['echopktin'] = peer_info['state']['echo'].get('received-packets', '0') if 'echo' in peer_info['state'] else ''
            temp['echopktout'] = peer_info['state']['echo'].get('transmitted-packets', '0') if 'echo' in peer_info['state'] else ''
            temp['zebranotifys'] = '0'
            temp['sessiondownev'] = peer_info['state'].get('failure-transitions', '')
            bfd_rest_data.append(temp)
        elif type == 'peers':
            temp['peer'] = peer_info.get('remote-address', '')
            temp['vrf_name'] = peer_info.get('vrf', '')
            temp['local_addr'] = peer_info.get('local-address') if peer_info.get('local-address') != 'null' else ''
            temp['interface'] = peer_info.get('interface', '')
            temp['label'] = ''
            uptime = peer_info['state'].get('last-up-time', '')
            uptime = calc_date_time(uptime)
            temp['uptimeday'] = uptime[0]
            temp['uptimehr'] = uptime[1]
            temp['uptimemin'] = uptime[2]
            temp['uptimesec'] = uptime[3]
            downtime = peer_info['state'].get('last-failure-time', '')
            downtime = calc_date_time(downtime)
            temp['downtimeday'] = downtime[0]
            temp['downtimehr'] = downtime[1]
            temp['downtimemin'] = downtime[2]
            temp['downtimesec'] = downtime[3]
            temp['local_id'] = peer_info['state'].get('local-discriminator', '')
            temp['remote_id'] = peer_info['state'].get('remote-discriminator', '')
            temp['status'] = peer_info['state'].get('session-state', '').lower()
            temp['diagnostics'] = peer_info['state'].get('local-diagnostic-code', '')
            temp['remote_diagnostics'] = peer_info['state'].get('remote-diagnostic-code', '')
            temp['peer_type'] = peer_info['state'].get('session-type', '').lower()
            temp['multiplier'] = [str(peer_info['state'].get('detection-multiplier', '')), str(peer_info['state'].get('remote-multiplier', ''))]
            temp['tx_interval'] = [str(peer_info['state'].get('desired-minimum-tx-interval', '')), str(peer_info['state'].get('remote-desired-transmission-interval', ''))]
            temp['rx_interval'] = [str(peer_info['state'].get('required-minimum-receive', '')), str(peer_info['state'].get('remote-minimum-receive-interval', ''))]
            temp['echo_tx_interval'] = [str(peer_info['state'].get('desired-minimum-echo-receive', '')), str(peer_info['state'].get('remote-echo-receive-interval', ''))]
            temp['err'] = ''
            bfd_rest_data.append(temp)
    st.banner("Rest Output")
    st.log('REST OUTPUT: {}'.format(bfd_rest_data))
    return bfd_rest_data
Пример #11
0
def test_ft_arp_static_route_config_mgmt_verifying_config_with_warm_reboot():
    '''
    Author: Surendra Kumar Vella([email protected])
    Verify static ARP route config after warm-reboot
    '''

    st.log("Checking whether the platform supports warm-reboot")
    if not data.platform.lower(
    ) in data.constants['WARM_REBOOT_SUPPORTED_PLATFORMS']:
        st.report_unsupported('test_case_unsupported')
    st.log("Performing warm-reboot on DUT")
    st.reboot(vars.D1, "warm")
    st.log("Verifying static route entries after save and warm-reboot")
    st.wait(5)
    static_route_verify()
    st.log("Verifying dynamic ARP entries after save and warm-reboot")
    if not arp_obj.verify_arp(vars.D1, data.ipv4_address_tgen,
                              data.src_mac_addr, vars.D1T1P1):
        st.report_fail("ARP_entry_dynamic_entry_fail", data.ipv4_address_tgen,
                       vars.D1)
    else:
        st.log("Verified that dynamic ARP entry is present in arp table")
    if st.get_ui_type(vars.D1) != "click":
        st.log("Verifying static ARP entries after save and warm-reboot")
        if not arp_obj.verify_arp(vars.D1, data.static_arp_ip,
                                  data.static_arp_mac, ""):
            st.report_fail("static_arp_create_fail", vars.D1)
        else:
            st.log("Verified that static ARP entry is present in arp table")
    st.report_pass("test_case_passed")
Пример #12
0
def verify_bfd_peer(dut,**kwargs):
    """
    author:[email protected]
    :param  :peer
    :type   :peer_ip address (list or string)
    :param  :local_addr
    :type   :local_address (list or string)
    :param  :interface
    :type   :bfd interface (list or string)
    :param  :local_id
    :type   :bfd local session-id (list or string)
    :param  :remote_id
    :type   :bfd remote session-d (list or string)
    :param  :status
    :type   :bfd session status (list or string)
    :param  :uptimeday
    :type   :uptime value in days (list or string)
    :param  :uptimehr
    :type   :uptime value in hours (list or string)
    :param  :uptimemin
    :type   :uptime value in minutes (list or string)
    :param  :uptimesec
    :type   :uptime value  in seconds (list or string)
    :param  :diagnostics
    :type   :diagnostics state (list or string)
    :param  :remote_diagnostics
    :type   :remote_diagnostics_state (list or string)
    :param  :rx_interval
    :type   :list of local_rx and remote_rx interval (list (or) list of lists)
    :param  :tx_interval
    :type   :list of local_rx and remote_tx interval (list (or) list of lists)
    :param  :echo_tx_interval
    :type   :list of local_echo_tx and remote_echo_tx interval (list (or) list of lists)
    :return :true/false
    :rtype  : boolean

    :Usage:
    bfd.verify_bfd_peer(dut1,peer='10.10.10.2',interface='Ethernet0',rx_interval=[['300','300']])
    bfd.verify_bfd_peer(dut1,peer=['10.10.10.2','20.20.20.2'],interface=['Ethernet0','Ethernet4'],status=['up','up'],diagnostics=['ok','nok'],rx_interval=[['300','300'],['300','300']])

    """
    if 'peer' not in kwargs:
        st.log("Mandatory parameter -peer not found")
        return False

    if 'vrf_name' in kwargs:
        vrf = kwargs['vrf_name']
        if vrf == 'default-vrf':
            vrf = 'default'
        del kwargs['vrf_name']
    else:
        vrf = 'default'

    cli_type = st.get_ui_type(dut, **kwargs)

    if 'multihop' in kwargs:
        is_mhop = True
        del kwargs['multihop']
        if 'local_addr' not in kwargs:
            st.error("-local_addr argument missing")
            return False
    else:
        is_mhop = False

    ping_verify = True if 'ping_verify' in kwargs else False
    kwargs.pop('ping_verify', '')

    rv = False
    #Converting all kwargs to list type to handle single or multiple peers
    for key in kwargs:
        if type(kwargs[key]) is list:
            kwargs[key] = list(kwargs[key])
        else:
            kwargs[key] = [kwargs[key]]

    #handling for multiple peers or single peer
    if len(kwargs['peer']) == 1:
        if is_mhop is False:
            if vrf == 'default':
                if 'local_addr' in kwargs and 'interface' in kwargs :
                    for peer_ip,local_addr,intf in zip(kwargs['peer'],kwargs['local_addr'],kwargs['interface']):
                        cmd = "show bfd peer " + peer_ip + " local-address "+ local_addr + " interface " + intf
                elif 'interface' in kwargs and 'local_addr' not in kwargs:
                    for peer_ip,intf in zip(kwargs['peer'],kwargs['interface']):
                        cmd = "show bfd peer " + peer_ip + " interface " + intf
                else:
                    for peer_ip,local_addr in zip(kwargs['peer'],kwargs['local_addr']):
                        cmd = "show bfd peer " + peer_ip + " local-address "+ local_addr
            else:
                if 'local_addr' in kwargs and 'interface' in kwargs :
                    if cli_type == 'click':
                        for peer_ip,local_addr,intf in zip(kwargs['peer'],kwargs['local_addr'],kwargs['interface']):
                            cmd = "show bfd" + " vrf " + vrf + " peer " + peer_ip + " local-address "+ local_addr + " interface " + intf
                    else:
                        for peer_ip,local_addr,intf in zip(kwargs['peer'],kwargs['local_addr'],kwargs['interface']):
                            cmd = "show bfd" + " peer " + peer_ip + " vrf " + vrf + " local-address "+ local_addr + " interface " + intf
                elif 'interface' in kwargs and 'local_addr' not in kwargs:
                    if cli_type == 'click':
                        for peer_ip,intf in zip(kwargs['peer'],kwargs['interface']):
                            cmd = "show bfd" + " vrf " + vrf + " peer " + peer_ip + " interface " + intf
                    else:
                        for peer_ip, intf in zip(kwargs['peer'], kwargs['interface']):
                            cmd = "show bfd" + " peer " + peer_ip + " vrf " + vrf + " interface " + intf
                else:
                    if cli_type == 'click':
                        for peer_ip,local_addr in zip(kwargs['peer'],kwargs['local_addr']):
                            cmd = "show bfd" + " vrf " + vrf + " peer " + peer_ip + " local-address "+ local_addr
                    else:
                        for peer_ip, local_addr in zip(kwargs['peer'], kwargs['local_addr']):
                            cmd = "show bfd" + " peer " + peer_ip + " vrf " + vrf + " local-address " + local_addr
        else:
            if vrf == 'default':
                for peer_ip, localaddress in zip(kwargs['peer'], kwargs['local_addr']):
                    cmd = "show bfd peer " + peer_ip + " multihop local-address " + localaddress
            else:
                if 'interface' not in kwargs and 'local_addr' in kwargs:
                    if cli_type == 'click':
                        for peer_ip, localaddress in zip(kwargs['peer'], kwargs['local_addr']):
                            cmd = "show bfd" + " vrf " + vrf + " peer " + peer_ip + " multihop local-address " + localaddress
                    else:
                        for peer_ip, localaddress in zip(kwargs['peer'], kwargs['local_addr']):
                            cmd = "show bfd" + " peer " + peer_ip + " vrf " + vrf + " multihop local-address " + localaddress
                elif 'interface' in kwargs and 'local_addr' in kwargs:
                    if cli_type == 'click':
                        for peer_ip, localaddress, intf in zip(kwargs['peer'], kwargs['local_addr'], kwargs['interface']):
                            cmd = "show bfd" + " vrf " + vrf + " peer " + peer_ip + " multihop local-address " + localaddress + " interface " + intf
                    else:
                        for peer_ip, localaddress, intf in zip(kwargs['peer'], kwargs['local_addr'], kwargs['interface']):
                            cmd = "show bfd" + " peer " + peer_ip + " vrf " + vrf + " multihop local-address " + localaddress + " interface " + intf
    else:
        if vrf == 'default':
            cmd = "show bfd peers"
        else:
            if cli_type == 'click':
                cmd = "show bfd" + " vrf " + vrf + " peers"
            else:
                cmd = "show bfd" + " peers" + " vrf " + vrf
    #Execute appropriate BFD CLI
    parsed_output = []
    if cli_type in ['click', 'klish']:
        cli_type = "vtysh" if cli_type == "click" else cli_type
        try:
            parsed_output = st.show(dut, cmd, type=cli_type)
        except Exception as e:
            st.error("The BFD session is not exist either deleted or not configured: exception is {} ".format(e))
            if ping_verify: debug_bfd_ping(dut, kwargs['peer'], vrf_name=vrf, cli_type=cli_type)
            return False
    elif cli_type in ['rest-patch', 'rest-put']:
        # st.show(dut, cmd, type='klish')
        bfd_type = 'multi' if is_mhop else 'single'
        if len(kwargs['peer']) > 1:
            parsed_output = rest_get_bfd_peer_info(dut, 'peers', bfd_type=bfd_type)
        else:
            st.log('Verifying single peer info')
            peer_ip = kwargs['peer'][0] if 'peer' in kwargs else ''
            local_addr = kwargs['local_addr'][0] if 'local_addr' in kwargs else ''
            st.log('peer_ip: {}, local_addr: {}'.format(peer_ip, local_addr))
            interface = kwargs['interface'][0] if 'interface' in kwargs else ''
            parsed_output = rest_get_bfd_peer_info(dut, 'peers', bfd_type=bfd_type, peer_list=False, vrf=vrf,
                                                   peer=peer_ip, local_addr=local_addr, interface=interface)
    else:
        st.error("Invalid UI-Type: {} provided".format(cli_type))
        return False

    if is_mhop: kwargs.pop('local_addr', '')

    if cli_type in ['klish', 'rest-patch', 'rest-put']:
        if 'status' in kwargs:
            kwargs['status'] = ['admin_down' if status == 'shutdown' else status for status in kwargs['status']]

    if 'return_dict' in kwargs:
        return parsed_output

    if len(parsed_output) == 0:
        st.error("OUTPUT is Empty")
        if ping_verify: debug_bfd_ping(dut, kwargs['peer'], vrf_name=vrf, cli_type=cli_type)
        return False
    #Get the index of peer from list of parsed output
    for i in range(len(kwargs['peer'])):
        peer_index = None
        st.log("Validation for BFD Peer : %s"%kwargs['peer'][i])
        for peer_info in parsed_output:
            if (peer_info['peer'] == kwargs['peer'][i]) and (peer_info['vrf_name'] == vrf and peer_info['status'] != ''):
                peer_index = parsed_output.index(peer_info)
        if peer_index is not None:
            #Iterate through the user parameters
            for k in kwargs.keys():
                if parsed_output[peer_index][k] == kwargs[k][i]:
                    st.log('Match Found for %s :: Expected: %s  Actual : %s'%(k,kwargs[k][i],parsed_output[peer_index][k]))
                    rv=True
                else:
                    st.error('Match Not Found for %s :: Expected: %s  Actual : %s'%(k,kwargs[k][i],parsed_output[peer_index][k]))
                    if ping_verify: debug_bfd_ping(dut, kwargs['peer'][i], vrf_name=vrf, enable_debug=False, cli_type=cli_type)
                    return False
        else:
            st.error(" BFD Peer %s not in output"%kwargs['peer'][i])
            if ping_verify: debug_bfd_ping(dut, kwargs['peer'], vrf_name=vrf, cli_type=cli_type)
            return False
    return rv
Пример #13
0
def verify_bfd_peers_brief(dut,**kwargs):
    """
    Author:[email protected]
    :param peeraddress:
    :type bfd-peer-address
    :param ouraddress:
    :type bfd-local-address
    :param status:
    :type up-or-down
    :param scount:
    :type session-count
    :param sessionid:
    :type bfd-session-id
    :param dut:
    :type dut:
    :return:
    :rtype:

    usage:
    bfd.verify_bfd_peers_brief(dut1,peeraddress="50.1.1.2",ouraddress="50.1.1.1",status="Up")
    bfd.verify_bfd_peers_brief(dut1,peeraddress="50.1.1.2",ouraddress="50.1.1.1",status="Shutdown")
    bfd.verify_bfd_peers_brief(dut1,peeraddress="5000::2",ouraddress="5000::1",status="Up")
    bfd.verify_bfd_peers_brief(dut1,peeraddress="5000::2",ouraddress="5000::1",status="Down")
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    cli_type = 'vtysh' if cli_type == 'click' else cli_type

    result = False
    st.log("Verify show bfd peers brief")
    output = get_bfd_peers_brief(dut, cli_type=cli_type)

    if len(output) == 0:
        st.error("Show OUTPUT is Empty")
        return result

    match_dict = {}
    if 'ouraddress' not in kwargs or 'peeraddress' not in kwargs:
        st.error("Mandatory parameters like ouraddress or/and peeraddress not passed")
        return result
    else:
        match_dict['peeraddress'] = kwargs['peeraddress']

    out_param = ['sessionid','status','scount','ouraddress']
    entries = filter_and_select(output,out_param, match_dict)

    if bool(entries):
        if 'status' in kwargs:
            if entries[0]['status'].lower() == kwargs['status'].lower() and entries[0]['ouraddress'] == kwargs['ouraddress']:
                result = True
                st.log("BFD session status is {} for peer {} Test Passed".format(entries[0]['status'],kwargs['peeraddress']))
            else:
                result = False
                st.error("BFD session status is not matching for src {} & peer {} Test Failed".format(kwargs['ouraddress'],kwargs['peeraddress']))
        if 'scount' in kwargs:
            if entries[0]['scount'] == kwargs['scount'] and entries[0]['ouraddress'] == kwargs['ouraddress']:
                result = True
                st.log("BFD session scount is {} for peer {} Test Passed".format(entries[0]['scount'],kwargs['peeraddress']))
            else:
                result = False
                st.error("BFD session scount is not matching for src {} & peer {} Test Failed".format(kwargs['ouraddress'],kwargs['peeraddress']))
        if 'status' not in kwargs and 'scount' not in kwargs:
            st.error("No arguments passed to be verified..")
    else:
        st.error("BFD session does not exist for peer address {} Test Failed".format(kwargs['peeraddress']))

    return result
Пример #14
0
def configure_bfd(dut, **kwargs):
    """
    Author:[email protected]
    :param local_asn:
    :type local-as-number:
    :param interface:
    :type interface:
    :param config:
    :type yes-or-no:
    :param neighbor_ip:
    :type neighbor-ip:
    :param multiplier:
    :type detect-multiplier:
    :param rx_intv:
    :type rx-interval:
    :param tx_intv:
    :type tx-interval:
    :param dut:
    :type dut:
    :return:
    :rtype:

    usage:
    configure_bfd(dut1, local_asn="10",neighbor_ip="50.1.1.2",config="yes")
    configure_bfd(dut1, local_asn="10",neighbor_ip="50.1.1.2",config="no")
    configure_bfd(dut1, local_asn="10",neighbor_ip="5000::2",config="yes")
    configure_bfd(dut1, interface="Ethernet0",neighbor_ip="50.1.1.2",multiplier="100",rx_intv="200",tx_intv="300" )
    configure_bfd(dut1, interface="Ethernet0",local_address="5000::1",neighbor_ip="5000::2",multiplier="100",rx_intv="200",tx_intv="300")
    configure_bfd(dut1, interface="Ethernet0",local_address="5000::1",neighbor_ip="5000::2",multiplier="100",rx_intv="200",tx_intv="300",multihop="yes")
    configure_bfd(dut1,local_address="10.1.1.1",neighbor_ip="20.1.1.1",multihop="yes",noshut="yes",label="abcd")
    configure_bfd(dut1,local_address="10.1.1.1",neighbor_ip="20.1.1.1",multihop="yes",shutdown="yes")
    """

    if 'vrf_name' in kwargs:
        vrf = kwargs['vrf_name']
        if vrf == 'default':
            vrf = 'default-vrf'
        del kwargs['vrf_name']
    else:
        vrf = 'default-vrf'

    cli_type = st.get_ui_type(dut, **kwargs)

    if 'neighbor_ip' not in kwargs:
        st.error("Mandatory parameter - neighbor_ip not found")
        return False

    peergroup = kwargs.get('peergroup', None)
    nbr_cmd = 'peer-group' if peergroup else 'neighbor'

    if 'config' in kwargs and kwargs['config'] == 'no':
        config=kwargs['config']
        del kwargs['config']
    else:
        config=''

    if 'multihop' in kwargs:
        multihop_cmd = 'multihop'
        del kwargs['multihop']
    else:
        multihop_cmd = ''

    #Converting all kwargs to list type to handle single or multiple peers
    for key in kwargs:
        if key != 'local_asn':
            if type(kwargs[key]) is list:
                kwargs[key] = list(kwargs[key])
            else:
                kwargs[key] = [kwargs[key]]

    #if 'local_asn' in kwargs and 'interface' not in kwargs:
    if 'local_asn' in kwargs:
        st.log("Entering router BGP..")
        if cli_type in ['click', 'klish']:
            if vrf == 'default-vrf':
                cmd = "router bgp {}\n".format(kwargs['local_asn'])
            else:
                cmd = "router bgp {} vrf {}\n".format(kwargs['local_asn'], vrf)
            for nbr in kwargs['neighbor_ip']:
                if cli_type == 'click':
                    cmd1 = cmd + "{} neighbor {} bfd \n".format(config, nbr)
                    st.config(dut, cmd1, type='vtysh')
                elif cli_type == 'klish':
                    if 'interface' in kwargs:
                        cmd1 = cmd + "{} interface {} \n {} bfd \n exit \n exit \n".format(nbr_cmd, nbr, config)
                    else:
                        cmd1 = cmd + "{} {} \n {} bfd \n exit \n exit \n".format(nbr_cmd, nbr, config)
                    st.config(dut, cmd1, type=cli_type)
        elif cli_type in ['rest-patch', 'rest-put']:
            vrf_str = 'default' if vrf == 'default-vrf' else vrf
            rest_urls = st.get_datastore(dut, "rest_urls")
            neigh_list = []
            for nbr in kwargs['neighbor_ip']:
                if not config:
                    neighbor_cmd = "neighbor-address" if nbr_cmd == 'neighbor' else "peer-group-name"
                    temp = {
                            neighbor_cmd: nbr,
                            "openconfig-bfd:enable-bfd": {"config": {"enabled": True, "openconfig-bgp-ext:bfd-check-control-plane-failure": True}}
                            }
                    neigh_list.append(temp)
                else:
                    neighbor_url = ["delete_bgp_neighbor_bfd_enabled", "delete_bgp_neighbor_bfd_cnpl_failure"] if nbr_cmd == 'neighbor' else ["delete_bgp_peergroup_bfd_enabled", "delete_bgp_peergroup_bfd_cnpl_failure"]
                    for url in neighbor_url:
                        url = rest_urls[url].format(vrf_str, nbr)
                        if not delete_rest(dut, http_method='delete', rest_url=url):
                            return False
            if not config:
                neighbor_url = "config_bgp_neighbor_list" if nbr_cmd == 'neighbor' else "config_bgp_peergroup_list"
                url = rest_urls[neighbor_url].format(vrf_str)
                data = {"openconfig-network-instance:{}".format(nbr_cmd): neigh_list}
                if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=data):
                    return False
        else:
            st.error("Invalid UI-Type: {} provided".format(cli_type))
            return False
    else:
        st.log("Entering BFD..")
        if cli_type in ['click', 'klish']:
            cmd ='bfd\n'
            for peer_index,nbr in zip(range(len(kwargs['neighbor_ip'])),kwargs['neighbor_ip']):
                if not multihop_cmd:
                    cmd += "{} peer {} ".format(config, nbr)
                else:
                    cmd += "{} peer {} {} ".format(config, nbr, multihop_cmd)

                if vrf == 'default-vrf':
                    if 'interface' in kwargs and "local_address" not in kwargs:
                        cmd += "interface {} \n".format(kwargs['interface'][peer_index])
                    elif 'interface' not in kwargs and "local_address" in kwargs:
                        cmd += "local-address {} \n".format(kwargs['local_address'][peer_index])
                    elif 'interface' in kwargs and "local_address" in kwargs:
                        cmd += "local-address {} interface {} \n".format(kwargs['local_address'][peer_index], kwargs['interface'][peer_index])
                else:
                    if 'interface' in kwargs and "local_address" not in kwargs:
                        cmd += "interface {} vrf {}\n".format(kwargs['interface'][peer_index], vrf)
                    elif 'interface' not in kwargs and "local_address" in kwargs:
                        cmd += "local-address {} vrf {}\n".format(kwargs['local_address'][peer_index], vrf)
                    elif 'interface' in kwargs and "local_address" in kwargs:
                        cmd += "local-address {} interface {} vrf {}\n".format(kwargs['local_address'][peer_index], kwargs['interface'][peer_index], vrf)

                if 'multiplier' in kwargs and config != 'no':
                    cmd += "detect-multiplier {} \n".format(kwargs['multiplier'][peer_index])
                if 'rx_intv' in kwargs and config != 'no':
                    cmd += "receive-interval {} \n".format(kwargs['rx_intv'][peer_index])
                if 'tx_intv' in kwargs and config != 'no':
                    cmd += "transmit-interval {} \n".format(kwargs['tx_intv'][peer_index])
                if 'noshut' in kwargs and config != 'no':
                    cmd += "no shutdown \n"
                if 'shutdown' in kwargs and config != 'no':
                    cmd += "shutdown \n"
                if 'echo_mode_enable' in kwargs and config != 'no':
                    cmd += "echo-mode \n"
                if 'echo_mode_disable' in kwargs and config != 'no':
                    cmd += "no echo-mode \n"
                if 'echo_intv' in kwargs and config != 'no':
                    cmd += "echo-interval {} \n".format(kwargs['echo_intv'][peer_index])
                if 'label' in kwargs and config != 'no':
                    cmd += "label {} \n".format(kwargs['label'][peer_index])
                if config != 'no':
                    cmd += 'exit \n'
            cmd += 'exit \n'
            if cli_type == 'click':
                st.config(dut,cmd, type='vtysh')
            elif cli_type == 'klish':
                st.config(dut, cmd, type=cli_type, faster_cli=False)
        elif cli_type in ['rest-patch', 'rest-put']:
            rest_urls = st.get_datastore(dut, "rest_urls")
            peer_type = 'multi' if multihop_cmd else 'single'
            vrf_str = 'default' if vrf == 'default-vrf' else vrf
            peer_list = []
            for peer_index, nbr in enumerate(kwargs['neighbor_ip']):
                temp = dict()
                temp['remote-address'] = nbr
                if 'interface' in kwargs: temp['interface'] = kwargs['interface'][peer_index]
                if 'multiplier' in kwargs: temp['detection-multiplier'] = int(kwargs['multiplier'][peer_index])
                if 'rx_intv' in kwargs: temp['required-minimum-receive'] = int(kwargs['rx_intv'][peer_index])
                if 'tx_intv' in kwargs: temp['desired-minimum-tx-interval'] = int(kwargs['tx_intv'][peer_index])
                if 'echo_mode_enable' in kwargs: temp['echo-active'] = True
                if 'echo_mode_disable' in kwargs: temp['echo-active'] = False
                if 'echo_intv' in kwargs: temp['desired-minimum-echo-receive'] = int(kwargs['echo_intv'][peer_index])
                if 'shutdown' in kwargs: temp['enabled'] = False
                if 'noshut' in kwargs: temp['enabled'] = True
                if 'local_address' in kwargs:
                    temp['local-address'] = kwargs['local_address'][peer_index]
                else:
                    temp['local-address'] = 'null'
                temp['vrf'] = vrf_str
                temp['enabled'] = temp.get('enabled', True)
                data = dict()

                data["remote-address"] = temp["remote-address"]
                data["vrf"] = temp["vrf"]
                data["interface"] = temp.get("interface", 'null')
                data["local-address"] = temp["local-address"]
                data['config'] = temp
                peer_list.append(data)
                if config == 'no':
                    hop_type = 'mhop' if peer_type == 'multi' else 'shop'
                    url = rest_urls['delete_bfd_peer'].format(hop_type, peer_type, data["remote-address"], data["interface"], data['vrf'], data["local-address"])
                    if not delete_rest(dut, http_method='delete', rest_url=url):
                        return False
            if not config:
                url = rest_urls['config_bfd_shop_peer_list'] if peer_type == 'single' else rest_urls['config_bfd_mhop_peer_list']
                data = {"openconfig-bfd-ext:{}-hop".format(peer_type): peer_list}
                if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=data):
                    return False
        else:
            st.error("Invalid UI-Type: {} provided".format(cli_type))
            return False
Пример #15
0
def qos_save_reboot_module_hooks(request):
    # add things at the start of this module
    global vars
    vars = dict()
    st.log("Ensuring minimum topology")
    vars = st.ensure_min_topology("D1T1:1")

    st.log("Configuring supported QoS features")
    wred_ecn_json_config = wred_config.wred_ecn_json_config
    st.log('Creating WRED and ECN table')
    utils.exec_all(True, [
        utils.ExecAllFunc(apply_wred_ecn_config, vars.D1, wred_ecn_json_config)
    ])
    st.log("Checking for wred config before save and reboot")
    wred_verify()
    st.log("checking for ecn config before save and reboot")
    ecn_verify()
    st.log("Configuring IPV4 ACL with rule")
    ipv4_acl_config()
    st.log("Configuring IPV6 ACL with rule")
    ipv6_acl_config()
    st.log("Checking for IPV4 ACL config before save and reboot")
    ipv4_acl_verify()
    st.log("Checking for IPV6 ACL config before save and reboot")
    ipv6_acl_verify()
    st.log("Configuring COS")
    cos_config()
    st.log("Checking for COS config before save and reboot")
    cos_config_verify()

    yield
    # add things at the end of this module"
    #Below step will clear COS, WRED and ECN config from the device.
    qos_obj.clear_qos_config(vars.D1)
    #Below step will clear all ACL config from the device.
    acl_obj.clear_acl_config(vars.D1)
Пример #16
0
def pre_config_ztp():
    global vars
    global ssh_conn_obj
    global outofband_conn_obj
    global ssh_conn_obj_oob_v6
    global ssh_conn_obj_inb_v6
    vars = st.get_testbed_vars()
    # DHCPV4 out of band params
    ztp_params.dhcp.ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "ip")
    ztp_params.dhcp.username = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "username")
    ztp_params.dhcp.password = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "password")
    ztp_params.oob_port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "interface")
    # DHCPV4 in band params
    ztp_params.dhcp.inband_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "ip")
    ztp_params.dhcp.inband_username = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "username")
    ztp_params.dhcp.inband_password = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "password")
    ztp_params.dhcp.inband_config_file = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "config_file")
    ztp_params.dhcp.inband_static_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "static_ip")
    ztp_params.inband_port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "interface")
    ztp_params.config_path = utils_obj.ensure_service_params(vars.D1, "ztp", "config_path")
    ztp_params.firmware_path = utils_obj.ensure_service_params(vars.D1, "ztp", "firmware_path")
    ztp_params.home_path = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "home_path")
    ztp_params.port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "port")
    ztp_params.build_file_name = utils_obj.ensure_service_params(vars.D1, "ztp", "build_file_name")
    ztp_params.uninstall_image = utils_obj.ensure_service_params(vars.D1, "ztp", "uninstall_image")
    ztp_params.dut_path = utils_obj.ensure_service_params(vars.D1, "ztp", "dut_path")
    ztp_params.ztp_cfg_file_name = utils_obj.ensure_service_params(vars.D1, "ztp", "ztp_cfg_file_name")
    ztp_params.provision_script_path = utils_obj.ensure_service_params(vars.D1, "ztp", "provision_script_path")
    ztp_params.docker_path = utils_obj.ensure_service_params(vars.D1, "ztp", "docker_path")
    ztp_params.docker_image = utils_obj.ensure_service_params(vars.D1, "ztp", "docker_image")
    ztp_params.docker_component_name = utils_obj.ensure_service_params(vars.D1, "ztp", "docker_component_name")
    ztp_params.inband_port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "interface")
    ztp_params.minigraph_file = utils_obj.ensure_service_params(vars.D1, "ztp", "minigraph_file")
    ztp_params.xml_path = utils_obj.ensure_service_params(vars.D1, "ztp", "xml_path")
    # DHCPV6 out of band params
    ztp_params.dhcp6.ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "ip")
    ztp_params.dhcp6.username = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "username")
    ztp_params.dhcp6.password = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "password")
    ztp_params.dhcp6.oob_port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "interface")
    ztp_params.dhcp6.oob_static_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "static_ip")
    # DHCPV6 IN band params
    ztp_params.dhcp6.inband_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "ip")
    ztp_params.dhcp6.inband_username = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "username")
    ztp_params.dhcp6.inband_password = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "password")
    ztp_params.dhcp6.inband_static_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "static_ip")
    ztp_params.dhcp6.inband_port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "interface")
    ztp_params.dhcp.inband_v4_subnet = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "subnet")
    ztp_params.dhcp.oob_v4_subnet= utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "subnet")
    ztp_params.dhcp6.inband_v6_subnet = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "subnet")
    ztp_params.dhcp6.oob_v6_subnet = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "subnet")
    ztp_params.dhcp.client_ip_inband = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "client_ip")
    ztp_params.breakout = utils_obj.ensure_service_params(vars.D1, "ztp", "breakout")
    ztp_params.cli_type = st.get_ui_type(vars.D1)
    st.log("Clearing V4/V6 lease database from DUT ...")
    basic_obj.delete_directory_contents(vars.D1, config_params.lease_db_path)
    st.log("################# Logging in to DHCPV4 server ---- IN BAND ...#################")
    ssh_conn_obj = con_obj.connect_to_device(ztp_params.dhcp.inband_ip,
                                             ztp_params.dhcp.inband_username, ztp_params.dhcp.inband_password)
    if not ssh_conn_obj:
        st.error("SSH connetion object not found for DHCPV4 server IN BAND.")
        reset_module_config()
        st.report_env_fail("ssh_connection_failed", ztp_params.dhcp.inband_ip)
    st.log("########Restarting DHCPV4 service##########")
    basic_obj.service_operations(ssh_conn_obj, config_params.dhcp_service_name, "restart", "server")
    st.log("########Verifying DHCPV4 service status##########")
    if not ztp_obj.verify_dhcpd_service_status(ssh_conn_obj, config_params.dhcpd_pid):
        st.log("{} service is not running ".format(config_params.dhcp_service_name))
        reset_module_config()
        st.report_fail("service_running_not_expected", config_params.dhcp_service_name)
    st.log("################# Logging in to DHCPV4 server ---- OUT OF BAND ... #################")
    outofband_conn_obj = con_obj.connect_to_device(ztp_params.dhcp.ip,
                                                   ztp_params.dhcp.username, ztp_params.dhcp.password)
    if not outofband_conn_obj:
        st.error("OUT OF BAND SSH connetion object not found.")
    else:
        basic_obj.service_operations(outofband_conn_obj, config_params.dhcp_service_name, "stop", "server")
        if ztp_obj.verify_dhcpd_service_status(outofband_conn_obj, config_params.dhcpd_pid):
            st.log("{} service is running which is not expected".format(config_params.dhcp_service_name))
            reset_module_config()
            st.report_fail("service_running_not_expected", config_params.dhcp_service_name)
        # st.report_env_fail("ssh_connection_failed", ztp_params.dhcp.ip)
    st.log("################# Logging in to DHCPV6 server -- OUT OF BAND ... #################")
    ssh_conn_obj_oob_v6 = con_obj.connect_to_device(ztp_params.dhcp6.ip,
                                                    ztp_params.dhcp6.username, ztp_params.dhcp6.password)
    if not ssh_conn_obj_oob_v6:
        st.error("SSH connection object not found for DHCPV6 server OUT OF BAND.")
    st.log("################# Logging in to DHCPV6 server ---- IN BAND ... ##################")
    ssh_conn_obj_inb_v6 = con_obj.connect_to_device(ztp_params.dhcp6.inband_ip,
                                                    ztp_params.dhcp6.inband_username, ztp_params.dhcp6.inband_password)
    if not ssh_conn_obj_inb_v6:
        st.error("SSH connection object not found for DHCPV6 server IN BAND.")
    st.log("Stopping V4/V6 services to avoid the DHCP option conflict .. ")
    v6_connection_objs = [ssh_conn_obj_inb_v6, ssh_conn_obj_oob_v6]
    for connection_obj in v6_connection_objs:
        if connection_obj:
            basic_obj.service_operations(connection_obj, config_params.dhcp6_service_name, "stop", "server")
            if ztp_obj.verify_dhcpd_service_status(connection_obj, config_params.dhcpd6_pid):
                st.log("{} service is running which is not expected".format(config_params.dhcp6_service_name))
                reset_module_config()
                st.report_fail("service_running_not_expected", config_params.dhcp6_service_name)
    basic_obj.poll_for_system_status(vars.D1)
    st.log("Shutting down the out of band interface ...")
    basic_obj.ifconfig_operation(vars.D1, ztp_params.oob_port, "down")
    ztp_cfg = {"admin-mode": True, "restart-ztp-interval": 30, "feat-console-logging": feat_logging_console}
    ztp_obj.config_ztp_backdoor_options(vars.D1, ztp_cfg)
Пример #17
0
def cos_config_verify():
    st.log(
        "verifying cos config is present in running-config - FtFpSoQoSCoSCfg001"
    )
    if not sconf_obj.verify_running_config(vars.D1, "TC_TO_QUEUE_MAP",
                                           data.cos_name, "0", "0"):
        st.report_fail("content_not_found")
    else:
        st.log("configuring cos queue mapping '0' is successful")
    if not sconf_obj.verify_running_config(vars.D1, "TC_TO_QUEUE_MAP",
                                           data.cos_name, "1", "1"):
        st.report_fail("content_not_found")
    else:
        st.log("configuring cos queue mapping '1' is successful")
    if not sconf_obj.verify_running_config(vars.D1, "TC_TO_QUEUE_MAP",
                                           data.cos_name, "2", "2"):
        st.report_fail("content_not_found")
    else:
        st.log("configuring cos queue mapping '2' is successful")
    if not sconf_obj.verify_running_config(vars.D1, "TC_TO_QUEUE_MAP",
                                           data.cos_name, "3", "3"):
        st.report_fail("content_not_found")
    else:
        st.log("configuring cos queue mapping '3' is successful")
    if not sconf_obj.verify_running_config(vars.D1, "TC_TO_QUEUE_MAP",
                                           data.cos_name, "4", "4"):
        st.report_fail("content_not_found")
    else:
        st.log("configuring cos queue mapping '4' is successful")
    if not sconf_obj.verify_running_config(vars.D1, "TC_TO_QUEUE_MAP",
                                           data.cos_name, "5", "5"):
        st.report_fail("content_not_found")
    else:
        st.log("configuring cos queue mapping '5' is successful")
    if not sconf_obj.verify_running_config(vars.D1, "TC_TO_QUEUE_MAP",
                                           data.cos_name, "6", "6"):
        st.report_fail("content_not_found")
    else:
        st.log("configuring cos queue mapping '6' is successful")
    if not sconf_obj.verify_running_config(vars.D1, "TC_TO_QUEUE_MAP",
                                           data.cos_name, "7", "7"):
        st.report_fail("content_not_found")
    else:
        st.log("configuring cos queue mapping '7' is successful")
Пример #18
0
def verify_ipv6_address_config():
    st.log("Verify ipv6 address on routing interface  {} in D1".format(
        vars.D1D2P1))
    if not ip_obj.verify_interface_ip_address(
            vars.D1, vars.D1D2P1, "{}/96".format(data.local_ip6_addr),
            data.af_ipv6):
        st.report_fail('ip6_routing_int_create_fail', vars.D1D2P1)
    else:
        st.log(" IPV6 Addres Config is successful")
    st.log("Verify ipv6 address on routing interface  {} in D2".format(
        vars.D2D1P1))
    if not ip_obj.verify_interface_ip_address(
            vars.D2, vars.D2D1P1, "{}/96".format(data.neigh_ip6_addr),
            data.af_ipv6):
        st.report_fail('ip6_routing_int_create_fail', vars.D2D1P1)
    else:
        st.log(" IPV6 Addres Config is successful")
    st.log("Verify ipv6 address on routing interface  {} in D1".format(
        vars.D1T1P2))
    if not ip_obj.verify_interface_ip_address(
            vars.D1, vars.D1T1P2, "{}/{}".format(
                data.d1t1_ip6_addr, data.d1t1_ip6_addr_mask), data.af_ipv6):
        st.report_fail('ipv6_routing_int_create_fail', vars.D1T1P2)
    else:
        st.log(" IPV6 Addres Config is successful")
Пример #19
0
def config_tc_to_pg_map(dut, obj_name, tc_to_pg_map_dict, **kwargs):
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type == 'click':
        final_data = dict()
        temp_data = dict()
        tc_to_pg_map_dict = get_non_range_map_data_from_range_map_data(
            tc_to_pg_map_dict)
        if not tc_to_pg_map_dict or not obj_name:
            st.log(
                "Please provide traffic class to priority group map dict. For example - {'0':'0', '1':'1', ...} and Object name like 'AZURE'"
            )
            return False
        else:
            temp_data[obj_name] = tc_to_pg_map_dict
        final_data['TC_TO_PRIORITY_GROUP_MAP'] = temp_data
        final_data = json.dumps(final_data)
        st.apply_json(dut, final_data)
    elif cli_type == 'klish':
        commands = list()
        commands.append('qos map tc-pg {}'.format(obj_name))
        for tc, pg in tc_to_pg_map_dict.items():
            commands.append('traffic-class {} priority-group {}'.format(
                tc, pg))
        commands.append('exit')
        response = st.config(dut, commands, type=cli_type)
        if any(error in response.lower() for error in errors_list):
            st.error("The response is: {}".format(response))
            return False
    elif cli_type in ['rest-patch', 'rest-put']:
        cli_type = 'rest-patch'
        rest_urls = st.get_datastore(dut, 'rest_urls')
        url = rest_urls['tc_pg_map_config']
        tc_to_pg_map_dict = get_non_range_map_data_from_range_map_data(
            tc_to_pg_map_dict)
        maps_data = [{
            "fwd-group": str(tc),
            "config": {
                "fwd-group": str(tc),
                "priority-group-index": int(pg)
            }
        } for tc, pg in tc_to_pg_map_dict.items()]
        tc_pg_map_data = {
            "openconfig-qos-maps-ext:forwarding-group-priority-group-map": [{
                "name":
                obj_name,
                "config": {
                    "name": obj_name
                },
                "forwarding-group-priority-group-map-entries": {
                    "forwarding-group-priority-group-map-entry": maps_data
                }
            }]
        }
        if not config_rest(
                dut, rest_url=url, http_method=cli_type,
                json_data=tc_pg_map_data):
            st.error("Failed to map TC to PG with data: {}".format(
                tc_to_pg_map_dict))
            return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True
Пример #20
0
def test_ft_bgp_fast_reboot():
    st.log("Enabling docker routing config mode in D1 and D2")
    bgp_obj.enable_docker_routing_config_mode(vars.D1)
    bgp_obj.enable_docker_routing_config_mode(vars.D2)
    st.log("saving the BGP config in vtysh shell")
    st.log("config save in D1 and D2")
    reboot_obj.config_save([vars.D1, vars.D2])
    st.log("Performing fast reboot")
    st.reboot(vars.D1, "fast")
    st.log("Verifying BGP is established after fast reboot")
    verify_v4_bgp_neigborship()
    if data.ipv6_support:
        st.log("Verifying BGPV6 is  established after fast reboot")
        verify_v6_bgp_neigborship()
    st.report_pass('test_case_passed')
Пример #21
0
def config_pfc_priority_to_queue_map(dut, obj_name,
                                     pfc_priority_to_queue_map_dict, **kwargs):
    """
    Author: Jagadish Chatrasi ([email protected])
    To map the PFC priority to queue
    :param dut:
    :type dut:
    :param obj_name:
    :type obj_name:
    :param pfc_priority_to_queue_map_dict:
    :type dict:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type == 'click':
        final_data = dict()
        temp_data = dict()
        pfc_priority_to_queue_map_dict = get_non_range_map_data_from_range_map_data(
            pfc_priority_to_queue_map_dict)
        if not pfc_priority_to_queue_map_dict or not obj_name:
            st.log(
                "Please provide pfc priority to queue map dict. For example - {'0':'0', '1':'1', ...} and Object name like 'AZURE'"
            )
            return False
        else:
            temp_data[obj_name] = pfc_priority_to_queue_map_dict
        final_data['MAP_PFC_PRIORITY_TO_QUEUE'] = temp_data
        final_data = json.dumps(final_data)
        st.apply_json(dut, final_data)
    elif cli_type == 'klish':
        commands = list()
        commands.append('qos map pfc-priority-queue {}'.format(obj_name))
        for pfc_priority, queue in pfc_priority_to_queue_map_dict.items():
            commands.append('pfc-priority {} queue {}'.format(
                pfc_priority, queue))
        commands.append('exit')
        response = st.config(dut, commands, type=cli_type)
        if any(error in response.lower() for error in errors_list):
            st.error("The response is: {}".format(response))
            return False
    elif cli_type in ['rest-patch', 'rest-put']:
        cli_type = 'rest-patch'
        rest_urls = st.get_datastore(dut, 'rest_urls')
        url = rest_urls['pfc_priority_queue_map_config']
        pfc_priority_to_queue_map_dict = get_non_range_map_data_from_range_map_data(
            pfc_priority_to_queue_map_dict)
        maps_data = [{
            "dot1p": int(dot1p),
            "config": {
                "dot1p": int(dot1p),
                "output-queue-index": int(queue)
            }
        } for dot1p, queue in pfc_priority_to_queue_map_dict.items()]
        pfc_priority_queue_map_data = {
            "openconfig-qos-maps-ext:pfc-priority-queue-map": [{
                "name": obj_name,
                "config": {
                    "name": obj_name
                },
                "pfc-priority-queue-map-entries": {
                    "pfc-priority-queue-map-entry": maps_data
                }
            }]
        }
        if not config_rest(dut,
                           rest_url=url,
                           http_method=cli_type,
                           json_data=pfc_priority_queue_map_data):
            st.error(
                "Failed to map PFC_PRIORITY to QUEUE with data: {}".format(
                    pfc_priority_to_queue_map_dict))
            return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True
Пример #22
0
def bgp_fast_reboot_module_hooks(request):
    global vars
    vars = st.ensure_min_topology("D1D2:1", "D1T1:2")
    if not st.is_feature_supported("bgp-neighbotship-performance", vars.D1):
        data.neighborship_wait = 30

    st.log("Enabling IPv6 mode globally")
    ip_obj.config_ipv6(vars.D1, action='enable')
    ip_obj.config_ipv6(vars.D2, action='enable')

    st.log("Configuring ipv4 addresses on routing interfaces")
    ipv4_ip_address_config()

    st.log("Verifying ipv4 addresses on routing interfaces")
    verify_ipv4_address_config()

    if data.ipv6_support:
        st.log("Configuring ipv6 addresses on routing interfaces")
        ipv6_address_config()
        st.log("Verifying ipv6 addresses on routing interfaces")
        verify_ipv6_address_config()
        st.log(
            "Configuring IPV6 eBGP config between DUT1 and DUT2,iBGP config between DUT1 and TG2"
        )
        ipv6_bgp_config()

    st.log(
        "Configuring IPV4 eBGP config between DUT1 and DUT2,iBGP config between DUT1 and TG1"
    )
    ipv4_bgp_config()

    if data.ipv6_support:
        st.log("Configuring TG2 V6 iBGP config")
        tg_bgpv6_config(vars, data.local_asn4, data.remote_asn4)

    st.log("Configuring TG1 V4 iBGP config")
    tg_bgp_config(vars, data.local_asn4, data.remote_asn4)

    st.log(
        "Verify IPV4 eBGP neighborship between D1 and D2 and iBGP neighborship between D1 and TG1"
    )
    verify_v4_bgp_neigborship()

    if data.ipv6_support:
        st.log(
            "Verify IPV6 eBGP neighborship between D1 and D2 and iBGP neighborship between D1 and TG2"
        )
        verify_v6_bgp_neigborship()

    yield

    bgp_obj.cleanup_router_bgp(st.get_dut_names())
    ip_obj.clear_ip_configuration(st.get_dut_names())

    if data.ipv6_support:
        ip_obj.clear_ip_configuration(st.get_dut_names(), 'ipv6')

    vlan_obj.clear_vlan_configuration(st.get_dut_names())
    portchannel_obj.clear_portchannel_configuration(st.get_dut_names())
Пример #23
0
def dhcp_relay_option_config(dut, **kwargs):
    """
    API for DHCP relay option configuration like link-selection, src-interface and max-hop count
    :param dut:
    :param kwargs:
    :return:
    """
    interface = kwargs.get("vlan", kwargs.get("interface", None))
    option = kwargs.get("option", None)
    src_interface = kwargs.get("src_interface", None)
    hop_count = kwargs.get("max_hop_count",0)
    policy_action = kwargs.get("policy_action",None)
    ip_family = kwargs.get("family", "ipv4")
    cli_type = st.get_ui_type(dut, **kwargs)
    skip_error_check = kwargs.get("skip_error_check", False)
    action = kwargs.get("action","add")

    if not (interface):
        st.error("required interface value is not passed")
        return False
    command = ""
    if cli_type == "click":
        if ip_family == "ipv4":
            if option == "policy-action":
                command = "config interface ip dhcp-relay policy-action {} {}".format(interface,policy_action)
            else:
                command = "config interface ip dhcp-relay {} {} {}".format(option, action, interface)
        else:
            command = "config interface ipv6 dhcp-relay {} {} {}".format(option, action, interface)

        if action == "add":
            if option == "src-intf":
                if not src_interface:
                    st.log("required src_interface value is not passed")
                    return False
                command += " {}".format(src_interface)
            if option == "max-hop-count":
                command += " {}".format(hop_count)
    elif cli_type == "klish":
        command = list()
        interface_data = get_interface_number_from_name(interface)
        command.append("interface {} {}".format(interface_data.get("type"), interface_data.get("number")))
        no_form = "" if action == "add" else "no"
        cmd = ""
        if ip_family == "ipv4":
            cmd += "{} ip dhcp-relay".format(no_form)
        else:
            cmd += "{} ipv6 dhcp-relay".format(no_form)
        if option == "src-intf":
            if not src_interface:
                if no_form != 'no':
                    st.error("Required 'src_interface' value is not passed")
                    return False
            src_interface = src_interface if no_form != "no" else ""
            cmd += " source-interface {}".format(src_interface)
        if option == "max-hop-count":
            max_hop_count = hop_count if no_form != "no" else ""
            cmd += " max-hop-count {}".format(max_hop_count)
        if option == "link-select":
            cmd += " link-select"
        if option == "vrf-select":
            cmd += " vrf-select"
        if option == "policy-action":
            cmd += " policy-action {}".format(policy_action)
        command.append(cmd)
    elif cli_type in ["rest-patch", "rest-put"]:
        config_dict = {'action': action, 'interface': interface, 'family': ip_family, 'cli_type': cli_type}
        if option == "src-intf":
            if not src_interface:
                if no_form != 'no':
                    st.error("required src_interface value is not passed")
                    return False
            config_dict['src_interface'] = src_interface
        elif option == "max-hop-count":
            config_dict['max_hop_count'] = hop_count
        elif option == "link-select":
            config_dict['link_select'] = True
        elif option == "vrf-select":
            config_dict['vrf_select'] = True
        elif option == "policy-action":
            config_dict['policy_action'] = policy_action
        else:
            st.error("Invalid option: {}".format(option))
            return False
        if not dhcp_relay_config(dut, **config_dict):
            st.error("Failed to set the option: {}".format(option))
            return False
    else:
        st.error("Unsupported CLI_type: {}".format(cli_type))
        return False
    if command:
        st.debug("command is {}".format(command))
        output = st.config(dut, command, skip_error_check=skip_error_check, type=cli_type)
        if "Error" in output:
            if skip_error_check:
                return True
            else:
                return False
    return True
Пример #24
0
def qos_warm_reboot_module_hooks(request):
    # add things at the start of this module
    init_vars()
    initialize_variables()
    get_parms()

    st.log("Checking whether the platform supports warm-reboot")
    if not data.platform.lower(
    ) in data.constants['WARM_REBOOT_SUPPORTED_PLATFORMS']:
        st.report_unsupported('test_case_unsupported')

    st.log("Configuring supported QoS features")
    wred_data = wred_config.init_vars(vars)
    st.log('Creating WRED and ECN table')
    putils.exec_all(True, [
        putils.ExecAllFunc(apply_wred_ecn_config, vars.D1,
                           wred_data['wred_ecn_json_config'])
    ])
    st.log("Checking for wred config before save and warm-reboot")
    wred_verify()
    st.log("checking for ecn config before save and warm-reboot")
    ecn_verify()
    st.log("Configuring IPV4 ACL with rule")
    ipv4_acl_config()
    st.log("Configuring IPV6 ACL with rule")
    ipv6_acl_config()
    st.log("Checking for IPV4 ACL config before save and warm-reboot")
    ipv4_acl_verify()
    st.log("Checking for IPV6 ACL config before save and warm-reboot")
    ipv6_acl_verify()
    st.log("Configuring COS")
    cos_config()
    st.log("Checking for COS config before save and warm-reboot")
    cos_config_verify()

    yield
    # add things at the end of this module"
    #Below step will clear COS, WRED and ECN config from the device.
    qos_obj.clear_qos_config(vars.D1)
    #Below step will clear all ACL config from the device.
    acl_obj.clear_acl_config(vars.D1)
Пример #25
0
def config_server(dut, no_form=False, skip_error_check=False, **kwargs):
    """
    Config / Unconfig radius server using provided parameters
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :param family:
    :param no_form:
    :param kwargs:
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    st.log("Configuring RADIUS SERVER Parameters ...")
    if "ip_address" not in kwargs:
        st.error("IP Address not provided")
        return False
    ipaddress_li = common_utils.make_list(kwargs["ip_address"])
    for each_ip in ipaddress_li:
        if cli_type == "klish":
            cmd = "radius-server host {}".format(each_ip)
            if "auth_type" in kwargs:
                cmd += " auth-type {}".format(kwargs["auth_type"])
            if "auth_port" in kwargs:
                cmd += " auth-port {}".format(kwargs["auth_port"])
            if "key" in kwargs:
                cmd += " key {}".format(kwargs["key"])
            if "priority" in kwargs:
                cmd += " priority {}".format(kwargs["priority"])
            if "timeout" in kwargs:
                cmd += " timeout {}".format(kwargs["timeout"])
            if "use_mgmt_vrf" in kwargs:
                cmd += " vrf {}".format(kwargs.get("use_mgmt_vrf"))
            if "retransmit" in kwargs:
                cmd += " re-transmit {}".format(kwargs["retransmit"])
            if "source_intf" in kwargs:
                cmd += " source-interface {}".format(kwargs["source_intf"])
            command = "no {}".format(cmd) if no_form else cmd
            st.config(dut,
                      command,
                      skip_error_check=skip_error_check,
                      type=cli_type)
        elif cli_type == "click":
            action = kwargs["action"] if "action" in kwargs else "add"
            command = "config radius {} {}".format(action, each_ip)
            if "retransmit" in kwargs:
                command += " -r {}".format(kwargs["retransmit"])
            if "auth_type" in kwargs:
                command += " -a {}".format(kwargs["auth_type"])
            if "timeout" in kwargs:
                command += " -t {}".format(kwargs["timeout"])
            if "key" in kwargs:
                command += " -k {}".format(kwargs["key"])
            if "auth_port" in kwargs:
                command += " -o {}".format(kwargs["auth_port"])
            if "priority" in kwargs:
                command += " -p {}".format(kwargs["priority"])
            if "use_mgmt_vrf" in kwargs:
                command += " -m"
            if "source_intf" in kwargs:
                if kwargs["source_intf"] == "Management0":
                    kwargs["source_intf"] = "eth0"
                command += " -s {}".format(kwargs["source_intf"])
            st.config(dut,
                      command,
                      type=cli_type,
                      skip_error_check=skip_error_check)
        elif cli_type in ["rest-patch", "rest-put"]:
            rest_urls = st.get_datastore(dut, "rest_urls")
            config_url = rest_urls['aaa_server_config']
            global_params = {"name": "RADIUS"}
            server_params = {"name": "RADIUS", "address": each_ip}
            radius_params = dict()
            radius_ext_params = dict()
            if "retransmit" in kwargs:
                if no_form:
                    del_url = rest_urls['radius_retransmit_config'].format(
                        'RADIUS', each_ip)
                    if not delete_rest(dut, rest_url=del_url,
                                       timeout=time_out):
                        st.error(
                            "Failed to remove retransmit config for {} server".
                            format(each_ip))
                        return False
                else:
                    radius_params.update(
                        {"retransmit-attempts": int(kwargs["retransmit"])})
            if "auth_type" in kwargs:
                if no_form:
                    del_url = rest_urls['radius_authtype_config'].format(
                        'RADIUS', each_ip)
                    if not delete_rest(dut, rest_url=del_url,
                                       timeout=time_out):
                        st.error(
                            "Failed to remove auth_type config for {} server".
                            format(each_ip))
                        return False
                else:
                    server_params.update({
                        "openconfig-system-ext:auth-type":
                        kwargs["auth_type"]
                    })
            if "timeout" in kwargs:
                if no_form:
                    del_url = rest_urls['radius_timeout_config'].format(
                        'RADIUS', each_ip)
                    if not delete_rest(dut, rest_url=del_url,
                                       timeout=time_out):
                        st.error(
                            "Failed to remove timeout config for {} server".
                            format(each_ip))
                        return False
                else:
                    server_params.update({"timeout": int(kwargs["timeout"])})
            if "key" in kwargs:
                if no_form:
                    del_url = rest_urls['radius_secretkey_config'].format(
                        'RADIUS', each_ip)
                    if not delete_rest(dut, rest_url=del_url,
                                       timeout=time_out):
                        st.error(
                            "Failed to remove key config for {} server".format(
                                each_ip))
                        return False
                else:
                    radius_params.update({"secret-key": kwargs["key"]})
            if "auth_port" in kwargs:
                if no_form:
                    del_url = rest_urls['radius_authport_config'].format(
                        'RADIUS', each_ip)
                    if not delete_rest(dut, rest_url=del_url,
                                       timeout=time_out):
                        st.error(
                            "Failed to remove auth-port config for {} server".
                            format(each_ip))
                        return False
                else:
                    radius_params.update(
                        {"auth-port": int(kwargs["auth_port"])})
            if "priority" in kwargs:
                if no_form:
                    del_url = rest_urls['radius_priority_config'].format(
                        'RADIUS', each_ip)
                    if not delete_rest(dut, rest_url=del_url,
                                       timeout=time_out):
                        st.error(
                            "Failed to remove priority config for {} server".
                            format(each_ip))
                        return False
                else:
                    server_params.update({
                        "openconfig-system-ext:priority":
                        int(kwargs["priority"])
                    })
            if "use_mgmt_vrf" in kwargs:
                if no_form:
                    del_url = rest_urls['radius_vrf_config'].format(
                        'RADIUS', each_ip)
                    if not delete_rest(dut, rest_url=del_url,
                                       timeout=time_out):
                        st.error(
                            "Failed to remove VRF config for {} server".format(
                                each_ip))
                        return False
                else:
                    server_params.update(
                        {"openconfig-system-ext:vrf": kwargs["use_mgmt_vrf"]})
            if "source_intf" in kwargs:
                if kwargs["source_intf"] == "Management0":
                    kwargs["source_intf"] = "eth0"
                if no_form:
                    del_url = rest_urls['radius_vrf_config'].format(
                        'RADIUS', each_ip)
                    if not delete_rest(dut, rest_url=del_url,
                                       timeout=time_out):
                        st.error(
                            "Failed to remove ipaddress config for {} server".
                            format(each_ip))
                        return False
                else:
                    radius_params.update({
                        "openconfig-aaa-radius-ext:source-interface":
                        kwargs["source_intf"]
                    })
            if "ip_address" in kwargs:
                if no_form:
                    del_url = rest_urls['radius_delete_server'].format(
                        'RADIUS', each_ip)
                    if not delete_rest(dut, rest_url=del_url,
                                       timeout=time_out):
                        st.error(
                            "Failed to remove ipaddress config for {} server".
                            format(each_ip))
                        return False
            if not no_form:
                config_data = {
                    "openconfig-system:server-group": [{
                        "name": "RADIUS",
                        "config": global_params,
                        "servers": {
                            "server": [{
                                "address": each_ip,
                                "config": server_params,
                                "radius": {
                                    "config": radius_params
                                }
                            }]
                        },
                        "openconfig-aaa-radius-ext:radius": {
                            "config": radius_ext_params
                        }
                    }]
                }
                if not config_rest(dut,
                                   http_method=cli_type,
                                   rest_url=config_url,
                                   json_data=config_data,
                                   timeout=time_out):
                    return False
        else:
            st.error("UNSUPPORTED CLI TYPE: {}".format(cli_type))
            return False
Пример #26
0
def apply_wred_ecn_config(dut, config):
    st.log("loading wred and ecn config from wred_ecn_config_json.py")
    json_config = json.dumps(config)
    json.loads(json_config)
    st.apply_json2(dut, json_config)
Пример #27
0
def show_config(dut, search_string="", cli_type=""):
    '''
    API to show the configured radius parameters
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :return:
    {'globals': [{global_auth_type': 'pap (default)','global_source_ip': '10.25.36.25','global_passkey': 'abcd (default)',
     'global_timeout': '5 (default)'}],
     'servers': [{'auth_type': '', 'passkey': '', 'auth_port': '1815', 'priority': '1', 'timeout': '', 'address': '1.1.1.5'},
      {'auth_type': '', 'passkey': '', 'auth_port': '1812', 'priority': '1', 'timeout': '', 'address': '1.1.1.1'}]}
    '''
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    st.log("Showing radius configuration ...")
    result = {"globals": [], "servers": []}
    if cli_type == "klish":
        command = "show radius-server"
        output = st.show(dut, command, type=cli_type)
        global_out = dict()
        if not output:
            return result
        for k, v in output[0].items():
            if "global" in k:
                global_out[k] = v
        if global_out:
            result["globals"].append(global_out)
        for d in output[0:]:
            server_out = dict()
            for k, v in d.items():
                if not "global" in k:
                    server_out[k] = v
            if server_out:
                result["servers"].append(server_out)
    elif cli_type == "click":
        command = "show radius | grep -w {}".format(
            search_string) if search_string else "show radius"
        output = st.show(dut, command, type=cli_type)
        for d in output:
            global_out = dict()
            server_out = dict()
            for k, v in d.items():
                if "global" in k:
                    global_out[k] = v
                else:
                    server_out[k] = v
            if global_out and not utils.check_empty_values_in_dict(global_out):
                result["globals"].append(global_out)
            if server_out and not utils.check_empty_values_in_dict(server_out):
                result["servers"].append(server_out)
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['radius_server_show'].format("RADIUS")
        url1 = rest_urls['radius_server_config'].format("RADIUS")
        url2 = rest_urls['radius_nasip_retransmit_stasitics_config'].format(
            "RADIUS")
        server_output = get_rest(dut, rest_url=url)
        global_config = get_rest(dut, rest_url=url1)
        global_ext_data = get_rest(dut, rest_url=url2)
        result = process_radius_output(server_output['output'],
                                       global_config['output'],
                                       global_ext_data['output'])
    else:
        st.log("UNSUPPORTED CLI TYPE")
        return False
    return result
Пример #28
0
def test_ft_qos_config_mgmt_verifying_config_with_save_reboot():
    st.log("performing Config save")
    rb_obj.config_save(vars.D1)
    st.log("performing reboot")
    st.reboot(vars.D1)
    st.log(
        "Checking whether config is loaded to running config from config_db after save and reboot"
    )
    st.log("Checking for IPV4 ACL config after save and reboot")
    ipv4_acl_verify()
    st.log("Checking for IPV6 ACL config after save and reboot")
    ipv6_acl_verify()
    st.log("Checking for COS config after save and reboot")
    cos_config_verify()
    st.log("Checking for wred config after save and reboot")
    wred_verify()
    st.log("checking for ecn config after save and reboot")
    ecn_verify()
    st.log(
        "configuration is successfully stored to config_db file after save and reboot"
    )
    st.report_pass("test_case_passed")
Пример #29
0
    def test_ipv6_confed_with_rr(self):
        st.log(
            "Verify the behavior of route-reflector within a confederation of BGPv6 peers"
        )
        st.log(
            "Consider the right confed iBGP_as and check RR functionality between the 3 iBGP routers"
        )

        network_ipv4 = '131.6.6.0/24'
        network_ipv6 = '3000:1::0/64'
        #IBGP as is one of D2/D3/D4 asn
        iBGP_as = topo['D2_as']

        bgpapi.config_bgp_network_advertise(topo['dut_list'][1], iBGP_as,
                                            network_ipv4)
        bgpapi.config_bgp_network_advertise(topo['dut_list'][1],
                                            iBGP_as,
                                            network_ipv6,
                                            addr_family='ipv6',
                                            config='yes')

        st.log(
            "Check the network on the 3rd IBGP peer is not learnt becaue RR is not configured"
        )
        entries = bgpapi.get_ip_bgp_route(topo['dut_list'][3],
                                          family="ipv4",
                                          network=network_ipv4)
        entries1 = bgpapi.get_ip_bgp_route(topo['dut_list'][3],
                                           family="ipv6",
                                           network="3000:1::/64")

        if entries and entries1:
            st.log("Routes learnt on the 3rd IBGP peer withour configuring RR")
            bgpapi.config_bgp_network_advertise(topo['dut_list'][1],
                                                iBGP_as,
                                                network_ipv4,
                                                config='no')
            bgpapi.config_bgp_network_advertise(topo['dut_list'][1],
                                                iBGP_as,
                                                network_ipv6,
                                                addr_family='ipv6',
                                                config='no')
            st.report_fail("test_case_failed")

        st.log(" Now configure RR")
        bgpapi.create_bgp_route_reflector_client(topo.dut_list[2], iBGP_as,
                                                 'ipv4',
                                                 topo['D3D4P1_neigh_ipv4'],
                                                 'yes')
        bgpapi.create_bgp_route_reflector_client(topo.dut_list[2], iBGP_as,
                                                 'ipv6',
                                                 topo['D3D4P1_neigh_ipv6'],
                                                 'yes')

        st.wait(10)
        st.log("Now the routes should be learnt on the 3rd IBGP peer")
        entries2 = bgpapi.get_ip_bgp_route(topo['dut_list'][3],
                                           family="ipv4",
                                           network=network_ipv4)
        entries3 = bgpapi.get_ip_bgp_route(topo['dut_list'][3],
                                           family="ipv6",
                                           network="3000:1::/64")

        bgpapi.config_bgp_network_advertise(topo['dut_list'][1],
                                            iBGP_as,
                                            network_ipv4,
                                            config='no')
        bgpapi.config_bgp_network_advertise(topo['dut_list'][1],
                                            iBGP_as,
                                            network_ipv6,
                                            addr_family='ipv6',
                                            config='no')
        bgpapi.create_bgp_route_reflector_client(topo.dut_list[2], iBGP_as,
                                                 'ipv4',
                                                 topo['D3D4P1_neigh_ipv4'],
                                                 'no')
        bgpapi.create_bgp_route_reflector_client(topo.dut_list[2], iBGP_as,
                                                 'ipv6',
                                                 topo['D3D4P1_neigh_ipv6'],
                                                 'no')

        if not entries2 and not entries3:
            st.report_fail("test_case_failed")

        st.report_pass("test_case_passed")
Пример #30
0
def nat_pre_config():
    global vars
    vars = st.ensure_min_topology("D1T1:2")
    platform = basic_obj.get_hwsku(vars.D1)
    common_constants = st.get_datastore(vars.D1, "constants", "default")
    if platform.lower() in common_constants['TH3_PLATFORMS']:
        st.error("NAT is not supported for this platform {}".format(platform))
        st.report_unsupported('NAT_unsupported_platform',platform)
    global tg_handler, tg1, tg2, tg_ph_1, tg_ph_2, dut1_rt_int_mac, tg_str_data, tg_rt_int_handle
    tg_handler = util_tg_init(vars, [vars.T1D1P1, vars.T1D1P2])
    tg1 = tg_handler["tg"]
    tg2 = tg_handler["tg"]
    tg_ph_1 = tg_handler["tg_ph_1"]
    tg_ph_2 = tg_handler["tg_ph_2"]
    ip_obj.config_ip_addr_interface(vars.D1, vars.D1T1P1, data.in1_ip_addr, data.in1_ip_addr_mask, family=data.af_ipv4)
    ip_obj.config_ip_addr_interface(vars.D1, vars.D1T1P2, data.out_ip_addr_l[0], data.out_ip_addr_mask, family=data.af_ipv4)
    dut1_rt_int_mac = basic_obj.get_ifconfig_ether(vars.D1, vars.D1T1P1)
    ip_obj.create_static_route(vars.D1, data.out_ip_addr_h,
                               "{}/{}".format(data.global_ip_addr_rt, data.global_ip_addr_mask),
                               shell=data.shell_vtysh, family=data.af_ipv4)
    ip_obj.create_static_route(vars.D1, data.in1_ip_addr_h[0], "{}/{}".format(data.s_global_ip_rt, data.s_global_ip_mask))
    tg_rt_int_handle = util_tg_routing_int_config(vars, tg1, tg2, tg_ph_1, tg_ph_2)
    st.log("NAT Configuration")
    nat_obj.config_nat_feature(vars.D1, 'enable')
    util_nat_zone_config(vars, [vars.D1T1P1, vars.D1T1P2], [data.zone_1, data.zone_2], config=data.config_add)
    nat_obj.config_nat_static(vars.D1, protocol=data.proto_all, global_ip=data.out_ip_addr_l[0],
                              local_ip=data.in1_ip_addr_h[0], config=data.config_add, nat_type=data.nat_type_dnat)
    nat_obj.config_nat_static(vars.D1, protocol=data.proto_tcp, global_ip=data.out_ip_addr_l[1],
                               local_ip=data.in1_ip_addr_h[1],
                               local_port_id=data.tcp_src_local_port, global_port_id=data.tcp_src_global_port,
                               config=data.config_add, nat_type=data.nat_type_dnat)
    nat_obj.config_nat_static(vars.D1, protocol=data.proto_udp, global_ip=data.in1_ip_addr_h[2],
                               local_ip=data.out_ip_addr_l[2],
                               local_port_id=data.udp_src_global_port, global_port_id=data.udp_src_local_port,
                               config=data.config_add, nat_type=data.nat_type_snat)
    nat_obj.config_nat_static(vars.D1, protocol=data.proto_all, global_ip=data.s_global_ip, local_ip=data.s_local_ip,
                              config=data.config_add, nat_type=data.nat_type_snat)
    nat_obj.config_nat_static(vars.D1,protocol=data.proto_all,global_ip=data.out_ip_addr_l[3],local_ip=data.in1_ip_addr_h[3],
                              config=data.config_add,nat_type=data.nat_type_dnat,twice_nat_id=data.twice_nat_id_1)
    nat_obj.config_nat_static(vars.D1, protocol=data.proto_all, global_ip=data.global_ip_addr,
                              local_ip=data.test_ip_addr,
                              config=data.config_add, nat_type=data.nat_type_snat, twice_nat_id=data.twice_nat_id_1)
    # dynamic NAT config
    st.log("Creating NAT Pool-1")
    nat_obj.config_nat_pool(vars.D1, pool_name=data.pool_name[0], global_ip_range=data.out_ip_range,
                            global_port_range= data.global_port_range, config=data.config_add)
    nat_obj.config_nat_pool(vars.D1, pool_name="scale_pool", global_ip_range="125.56.90.23-125.56.90.30",
                            global_port_range="1001-8001", config=data.config_add)
    st.log("Creating NAT Pool binding")
    nat_obj.config_nat_pool_binding(vars.D1, binding_name=data.bind_name[0], pool_name=data.pool_name[0],
                                    config=data.config_add)
    st.log("Creating NAT Pool-2")
    nat_obj.config_nat_pool(vars.D1, pool_name=data.pool_name[1], global_ip_range=data.out2_ip_range,
                             config=data.config_add)
    st.log("Creating NAT Pool-2 binding")
    nat_obj.config_nat_pool_binding(vars.D1, binding_name=data.bind_name[1], pool_name=data.pool_name[1],
                                    config=data.config_add)
    # nat acl for ingress traffic
    acl_obj.create_acl_table(vars.D1, name=data.acl_table_in_nat_eg, stage="INGRESS", type=data.type,
                             description="ingress-acl", ports=[vars.D1T1P1])
    acl_obj.create_acl_rule(vars.D1, table_name=data.acl_table_in_nat_eg, rule_name="rule-32", packet_action=data.packet_forward_action,
                            SRC_IP="{}/{}".format(data.in1_ip_addr_rt, data.in1_ip_addr_mask), priority='98', type=data.type, ip_protocol="4")
    acl_obj.create_acl_rule(vars.D1, table_name=data.acl_table_in_nat_eg, rule_name="rule-33",
                            packet_action=data.packet_do_not_nat_action,
                            SRC_IP="{}/{}".format('14.1.0.1', data.mask), priority='97', type=data.type, ip_protocol="4")
    # Checking arp table for debugging
    arp_obj.show_arp(vars.D1)
    ip_obj.show_ip_route(vars.D1)
    # Clearing all interface counters for debugging purpose
    intf_obj.clear_interface_counters(vars.D1)
    tg_str_data = util_tg_stream_config(tg1, tg2, tg_ph_1, tg_ph_2)