Exemplo n.º 1
0
def config_nat_interface(dut, **kwargs):
    """
    Config NAT interface
    Author:[email protected]
    :param :dut:
    :param :config: add-del:
    :param :interface_name:
    :param :zone_value:

    usage:
    config_nat_interface(dut1, interface_name, zone_value, config="add")
    config_nat_interface(dut1, interface_name, config="del")
    """
    result = False
    command = ''
    cli_type = st.get_ui_type(dut, **kwargs)
    skip_error_check = kwargs.get("skip_error_check", True)
    if cli_type not in ["klish", "click", "rest-patch", "rest-put"]:
        st.log("UNSUPPORTE CLI TYPE")
        return False
    if "interface_name" not in kwargs and "config" not in kwargs:
        st.error("Mandatory params interface_name or config not provided")
        return result
    if kwargs["config"] == "add":
        if "zone_value" not in kwargs:
            st.error("Mandatory params zone_vlaue not provided")
            return result
        if cli_type == "click":
            command = "config nat add interface {} -nat_zone {}".format(kwargs["interface_name"], kwargs["zone_value"])
        elif cli_type == "klish":
            command = list()
            intf_data = get_interface_number_from_name(kwargs["interface_name"])
            command.append("interface {} {}".format(intf_data["type"], intf_data["number"]))
            command.append("nat-zone {}".format(kwargs["zone_value"]))
            command.append("exit")
        elif cli_type in ["rest-patch", "rest-put"]:
            url = st.get_datastore(dut, "rest_urls")['config_nat_interface'].format(kwargs["interface_name"])
            data = {"openconfig-interfaces-ext:nat-zone": int(kwargs["zone_value"])}
            config_rest(dut, http_method=cli_type, rest_url=url, json_data=data)
            return True

    if kwargs["config"] == "del":
        if cli_type == "click":
            command = "config nat remove interface {}".format(kwargs["interface_name"])
        elif cli_type == "klish":
            command = list()
            intf_data = get_interface_number_from_name(kwargs["interface_name"])
            command.append("interface {} {}".format(intf_data["type"], intf_data["number"]))
            command.append("no nat-zone")
            command.append("exit")
        elif cli_type in ["rest-patch", "rest-put"]:
            url = st.get_datastore(dut, "rest_urls")['del_nat_interface'].format(kwargs["interface_name"])
            delete_rest(dut, rest_url=url)
            return True

    st.config(dut, command, type=cli_type, skip_error_check=skip_error_check)
    return True
Exemplo n.º 2
0
def config_stp_vlan_interface(dut, vlan, iface, value, mode='cost', **kwargs):
    """

    :param dut:
    :param vlan:
    :param iface:
    :param value:
    :param mode:
    :return:
    """
    cli_type = kwargs.get('cli_type', 'click')
    no_form = 'no' if kwargs.get('no_form') else ''

    if mode in ['cost', 'priority']:
        if cli_type == 'click':
            command = "config spanning_tree vlan interface {} {} {} {} ".format(
                mode, vlan, iface, value)
        elif cli_type == 'klish':
            if mode == 'priority':
                mode = 'port-priority'
            interface_data = utils.get_interface_number_from_name(iface)
            command = [
                'interface {} {}'.format(interface_data["type"],
                                         interface_data["number"]),
                '{} spanning-tree vlan {} {} {}'.format(
                    no_form, vlan, mode, value), "exit"
            ]
        else:
            st.error("Invalid CLI type - {}".format(cli_type))
            return
    else:
        st.log("Invalid mode = {}".format(mode))
        return
    st.config(dut, command, type=cli_type)
Exemplo n.º 3
0
def config_port_type(dut,
                     interface,
                     stp_type="rpvst",
                     port_type="edge",
                     no_form=False,
                     cli_type="klish"):
    """
    API to config/unconfig the port type in RPVST
    :param dut:
    :param port_type:
    :param no_form:
    :return:
    """
    commands = list()
    command = "spanning-tree port type {}".format(
        port_type) if not no_form else "no spanning-tree port type"
    interface_details = utils.get_interface_number_from_name(interface)
    if not interface_details:
        st.log("Interface details not found {}".format(interface_details))
        return False
    commands.append("interface {} {}".format(interface_details.get("type"),
                                             interface_details.get("number")))
    commands.append(command)
    commands.append('exit')
    st.config(dut, commands, type=cli_type)
    return True
Exemplo n.º 4
0
def clear_mac_dampening(dut, **kwargs):
    """
    Author :
    :param dut:
    :param interface:
    :return:
    usage
    clear_mac_dampening(dut1,interface="Ethernet0")
    clear_mac_dampening(dut1)
    """

    cli_type = kwargs.get("cli_type", st.get_ui_type(dut))
    if cli_type in ["click", "rest-put", "rest-patch"]: cli_type = 'klish'
    if cli_type == "klish":
        if 'interface' in kwargs:
            intf_data = get_interface_number_from_name(kwargs['interface'])
            command = "clear mac dampening-disabled-ports {} {}\n".format(
                intf_data["type"], intf_data["number"])
        else:
            command = "clear mac dampening-disabled-ports all\n"
    elif cli_type in ["rest-put", "rest-patch"]:
        st.log('Needs to add rest url support')
        #url = st.get_datastore(dut, "rest_urls")["config_interface"]
        #if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=):
        #return False
    else:
        st.log("Unsupported CLI TYPE {}".format(cli_type))
        return False
    if command:
        st.config(dut, command, type=cli_type)
    return True
Exemplo n.º 5
0
def verify_intf_diag_loopback_cap(dut, intf, **kwargs):
    '''
	:param ms_hs_loopback:
	:param pl_ms_loopback:
	:param pl_hs_loopback:
	:param hs_ip_loopback:
	:param hs_op_loopback:
	:param ms_ip_loopback:
	:param ms_op_loopback:

    '''
    st.log('API: verify_intf_diag_reporting - DUT: {}, intf: {}, kwargs: {}'.
           format(dut, intf, kwargs))
    #cli_type = kwargs.pop('cli_type', st.get_ui_type(dut,**kwargs))
    kwargs.pop('cli_type', None)

    num_args = len(kwargs)
    intf_info = get_interface_number_from_name(intf)
    cmd = 'show interface transceiver diagnostics loopback capability {} {}'.format(
        intf_info['type'], intf_info['number'])
    cmd_output = st.show(dut, cmd, type='klish')

    for kv in kwargs.items():
        if not filter_and_select(cmd_output, None, {kv[0]: kv[1]}):
            st.error('{} is not matching on {}'.format(kv[0], dut))
        else:
            num_args -= 1

    return True if num_args == 0 else False
Exemplo n.º 6
0
def clear_mac(dut,port=None,vlan=None,**kwargs):
    """
    This proc is to clear mac address/fdb entries of the dut.
    :param dut: DUT Number
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    cli_type = 'klish' if cli_type in ['rest-patch', 'rest-put'] else cli_type
    if cli_type == "click":
        if not st.is_feature_supported("sonic-clear-fdb-type-command", dut):
            command = "sonic-clear fdb all"
        elif port:
            command = "sonic-clear fdb port {}".format(port)
        elif vlan:
            command = "sonic-clear fdb vlan Vlan{}".format(vlan)
        else:
            command = "sonic-clear fdb all"
        st.config(dut, command, type=cli_type)
    elif cli_type == "klish":
        if 'address' in kwargs:
            command = "clear mac address-table dynamic address  {}".format(kwargs['address'])
        elif vlan:
            command = "clear mac address-table dynamic Vlan {}".format(vlan)
        elif port:
            intf_data = get_interface_number_from_name(port)
            command = "clear mac address-table dynamic interface {} {}".format(intf_data["type"],intf_data["number"])
        else:
            command = "clear mac address-table dynamic all"

        st.config(dut, command,type=cli_type)
    else:
        st.error("Unsupported CLI: {}".format(cli_type))
        return False
    return True
Exemplo n.º 7
0
def config_mac(dut, mac, vlan, intf, cli_type=""):
    """
    :param dut:
    :type dut:
    :return:
    :rtype:
    """
    #st.log("config mac add <mac> <vlan> <intf>")
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if cli_type == 'click':
        command = "config mac add {} {} {}".format(mac, vlan, intf)
        if not st.is_feature_supported("config-mac-add-command", dut):
            st.community_unsupported(command, dut)
            _json_mac_add(dut, mac, vlan, intf)
        else:
            st.config(dut, command, type='click')
    elif cli_type == 'klish':
        interface = get_interface_number_from_name(intf)
        command = "mac address-table {} vlan {} {} {}".format(
            mac, vlan, interface["type"], interface["number"])
        st.config(dut, command, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['static_mac_config']
        json = {
            "openconfig-network-instance:network-instances": {
                "network-instance": [{
                    "name": "default",
                    "fdb": {
                        "mac-table": {
                            "entries": {
                                "entry": [{
                                    "mac-address": mac,
                                    "vlan": int(vlan),
                                    "config": {
                                        "mac-address": mac,
                                        "vlan": int(vlan)
                                    },
                                    "interface": {
                                        "interface-ref": {
                                            "config": {
                                                "interface": intf,
                                                "subinterface": 0
                                            }
                                        }
                                    }
                                }]
                            }
                        }
                    }
                }]
            }
        }
        if not config_rest(
                dut, http_method=cli_type, rest_url=url, json_data=json):
            return False
    else:
        st.log("Unsupported cli")
        return False
    return True
Exemplo n.º 8
0
def clear_port_shaper(dut, port='', shaper_data='', **kwargs):
    """
    API to clear shaper and detach shaper from port
    :param dut:
    :type dut:
    :param port:
    :type port:
    :param shaper_data:
    :type shaper_data:
    :param cli_type:
    :type cli_type:
    :return:
    :rtype:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    skip_error = kwargs.get('skip_error', False)
    cli_type = 'klish' if skip_error and cli_type == 'click' else cli_type
    qos_clear = kwargs.get('qos_clear', False)
    remove_shaper = kwargs.get('remove_shaper', True)
    if (not qos_clear) and cli_type == 'click':
        cli_type = 'klish'
    if cli_type == 'click':
        clear_qos_config(dut)
    elif cli_type == 'klish':
        commands = list()
        if port:
            intf_data = get_interface_number_from_name(port)
            commands.append("interface {} {}".format(intf_data['type'],
                                                     intf_data['number']))
            commands.append("no scheduler-policy")
            commands.append("exit")
        if shaper_data and remove_shaper:
            commands.append("no qos scheduler-policy {}".format(shaper_data))
        response = st.config(dut,
                             commands,
                             type=cli_type,
                             skip_error_check=skip_error)
        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']:
        rest_urls = st.get_datastore(dut, "rest_urls")
        if port:
            url = rest_urls['policy_apply_config'].format(port)
            if not delete_rest(dut, rest_url=url):
                st.error(
                    "Failed to remove scheduler-policy on port: {}".format(
                        port))
                return False
        if shaper_data and remove_shaper:
            url = rest_urls['scheduler_policy_config'].format(shaper_data)
            if not delete_rest(dut, rest_url=url):
                st.error("Failed to remove QOS scheduler-policy: {}".format(
                    shaper_data))
                return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True
Exemplo n.º 9
0
def add_static_arp(dut, ipaddress, macaddress, interface="", cli_type=""):
    """
    To add static arp
    Author: Prudvi Mangadu ([email protected])
    :param dut:
    :param ipaddress:
    :param macaddress:
    :param interface:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    command = ''
    if cli_type == "click":
        command = "arp -s {} {}".format(ipaddress, macaddress)
        if interface:
            command += " -i {}".format(interface)
    elif cli_type == "klish":
        if interface:
            intf = get_interface_number_from_name(interface)
            command = "interface {} {}".format(intf['type'], intf['number'])
            command = command + "\n" + "ip arp {} {}".format(
                ipaddress, macaddress) + "\n" + "exit"
        else:
            st.error(
                "'interface' option is mandatory for adding static arp entry in KLISH"
            )
            return False
    elif cli_type in ['rest-patch', 'rest-put']:
        if not interface:
            st.error(
                "'interface' option is mandatory for adding static arp entry in REST"
            )
            return False
        port_index = get_subinterface_index(dut, interface)
        rest_urls = st.get_datastore(dut, 'rest_urls')
        url = rest_urls['config_static_arp'].format(name=interface,
                                                    index=port_index)
        config_data = {
            "openconfig-if-ip:neighbor": [{
                "ip": ipaddress,
                "config": {
                    "ip": ipaddress,
                    "link-layer-address": macaddress
                }
            }]
        }
        if not config_rest(
                dut, rest_url=url, http_method=cli_type,
                json_data=config_data):
            st.error(
                "Failed to configure static ARP with IP: {}, MAC: {}, INTF: {}"
                .format(ipaddress, macaddress, interface))
            return False
    else:
        st.error("Unsupported CLI_TYPE: {}".format(cli_type))
        return False
    if command:
        st.config(dut, command, type=cli_type)
    return True
Exemplo n.º 10
0
def config_intf_udld_mode(dut, **kwargs):
    """
    config_intf_udld_mode(dut=data.dut1,intf ='Ethernet10',udld_mode='yes',config='yes')
    config_intf_udld_mode(dut=data.dut1,intf ='Ethernet10',udld_mode='yes')
    config_intf_udld_mode(dut=data.dut1,intf ='Ethernet10',udld_mode='',config='no')
    udld.config_intf_udld_mode(dut=dut2,intf ='Ethernet37',udld_mode='yes',config='yes',cli_type='rest-put')
    Author: [email protected]
    Enable UDLD mode Aggressive at interface level
    :param dut:
    :param intf:
    :param udld_mode:
    :return:
    """
    cli_type = kwargs.pop('cli_type', st.get_ui_type(dut))
    if 'config' in kwargs:
        config = kwargs['config']
    else:
        config = 'yes'
    if config.lower() == 'yes':
        config_cmd = ''
    else:
        config_cmd = 'no'
    if 'intf' in kwargs:
        if type(kwargs['intf']) is list:
            kwargs['intf'] = list(kwargs['intf'])
        else:
            kwargs['intf'] = [kwargs['intf']]
    my_cmd = ''
    if cli_type == 'klish' or cli_type == 'click':
        for intf in kwargs['intf']:
            intf_details = get_interface_number_from_name(intf)
            my_cmd += 'interface {} {}\n'.format(intf_details['type'],
                                                 intf_details['number'])
            if 'udld_mode' in kwargs:
                my_cmd += '{} udld aggressive\n'.format(config_cmd)
                my_cmd += 'exit\n'
        st.config(dut, my_cmd, type='klish')
    elif cli_type in ['rest-patch', 'rest-put']:
        http_method = kwargs.pop('http_method', cli_type)
        rest_urls = st.get_datastore(dut, 'rest_urls')
        for intf in kwargs['intf']:
            rest_url = rest_urls['udld_interface_aggressive_config'].format(
                intf)
            if config_cmd == '':
                ocdata = {"openconfig-udld-ext:aggressive": bool(1)}
            else:
                ocdata = {"openconfig-udld-ext:aggressive": bool(0)}
            response = config_rest(dut,
                                   http_method=http_method,
                                   rest_url=rest_url,
                                   json_data=ocdata)
            if not response:
                st.log('UDLD mode for interface config/unconfig failed')
                st.log(response)
                return False
            return True
    else:
        st.log("Unsupported CLI TYPE - {}".format(cli_type))
        return False
Exemplo n.º 11
0
def show_ndp(dut, inet6_address=None, **kwargs):
    """
    to get ndp table info
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :param inet6_address:
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type == "click":
        if 'vrf' not in kwargs:
            command = "show ndp"
            if inet6_address:
                command += " {}".format(inet6_address)
            elif "interface" in kwargs and kwargs["interface"]:
                command += " -if {}".format(kwargs["interface"])
        elif 'vrf' in kwargs:
            vrf = kwargs['vrf']
            command = "show ndp -vrf {}".format(vrf)
            if inet6_address:
                command += " {}".format(inet6_address)
            elif "interface" in kwargs and kwargs["interface"]:
                command += " -if {}".format(kwargs["interface"])
    elif cli_type == "klish":
        if 'vrf' not in kwargs:
            command = "show ipv6 neighbors"
            if inet6_address:
                command += " {}".format(inet6_address)
            elif kwargs.get("interface"):
                intf = get_interface_number_from_name(kwargs.get("interface"))
                command += " interface {} {}".format(intf["type"],
                                                     intf["number"])
        elif 'vrf' in kwargs:
            vrf = kwargs['vrf']
            command = "show ipv6 neighbors vrf {}".format(vrf)
            if inet6_address:
                command += " {}".format(inet6_address)
    elif cli_type in ["rest-patch", "rest-put"]:
        output = list()
        if kwargs.get('vrf'):
            interfaces = _get_rest_l3_interfaces(dut, vrf=kwargs['vrf'])
        else:
            interfaces = _get_rest_l3_interfaces(dut)
        for interface in interfaces:
            output.extend(
                _get_rest_neighbor_entries(dut, interface, is_arp=False))
        st.debug(output)
        if inet6_address:
            return filter_and_select(output, None, {'address': inet6_address})
        elif kwargs.get('interface'):
            return filter_and_select(output, None,
                                     {'interface': kwargs['interface']})
        else:
            return output
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return st.show(dut, command, type=cli_type)
Exemplo n.º 12
0
def test_ft_snmp_dot1d_base_port():
    """
    Author : Prasad Darnasi<*****@*****.**>
    Verify that the dot1dBasePort Object functions properly.
    Reference Test Bed : D1 --- Mgmt Network
    """
    get_snmp_output = snmp_obj.walk_snmp_operation(
        ipaddress=ipaddress,
        oid=data.oid_dot1d_Base_Port,
        community_name=data.ro_community,
        filter=data.filter)
    intf_name1 = util_obj.get_interface_number_from_name(vars.D1T1P1)
    intf_name2 = util_obj.get_interface_number_from_name(vars.D1T1P2)
    if (intf_name1.get('number')
            not in str(get_snmp_output)) and (intf_name2.get('number')
                                              not in str(get_snmp_output)):
        st.report_fail("snmp_output_failed", "dot1dBasePort")
    st.report_pass("test_case_passed")
Exemplo n.º 13
0
def delete_vlan_member(dut,
                       vlan,
                       port_list,
                       participation_mode="trunk",
                       cli_type="",
                       skip_error_check=False):
    """
    Delete Members in VLAN
    Author : Prudvi Mangadu ([email protected])

    :param dut:
    :param vlan:
    :param port_list:
    :param participation_mode:
    :param cli_type:
    :return:
    """
    if not cli_type:
        cli_type = st.get_ui_type(dut)

    st.log("Delete member from the VLAN")
    port_li = list(port_list) if isinstance(port_list, list) else [port_list]
    commands = list()
    for each_port in port_li:
        if cli_type == "click":
            command = "config vlan member del {} {}".format(vlan, each_port)
            out = st.config(dut, command, skip_error_check=skip_error_check)
            if "is not a member of Vlan{}".format(vlan) in out:
                st.error("{} is not a member of Vlan{}".format(
                    each_port, vlan))
                return False
            if "Vlan{} doesn't exist".format(vlan) in out:
                st.error("Vlan{} doesn't exist".format(vlan))
                return False
        else:
            interface_details = get_interface_number_from_name(each_port)
            if not interface_details:
                st.log(
                    "Interface details not found {}".format(interface_details))
                return False
            commands.append("interface {} {}".format(
                interface_details.get("type"),
                interface_details.get("number")))
            if participation_mode == "trunk":
                command = "switchport trunk allowed Vlan {}".format(vlan)
                commands.append("no {}".format(command))
            elif participation_mode == "access":
                command = "switchport access Vlan".format(vlan)
                commands.append("no {}".format(command))
            commands.append("exit")
    if commands:
        st.config(dut,
                  commands,
                  type=cli_type,
                  skip_error_check=skip_error_check)
    return True
Exemplo n.º 14
0
def show_arp(dut, ipaddress=None, interface=None, vrf="", cli_type=""):
    """
    To get arp table info
    Author: Prudvi Mangadu ([email protected])
    :param dut:
    :param ipaddress:
    :param interface:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if cli_type == "click":
        if vrf == "":
            command = "show arp"
            if ipaddress:
                command += " {}".format(ipaddress)
            elif interface:
                command += " -if {}".format(interface)
        elif vrf != "":
            command = "show arp -vrf {}".format(vrf)
            if ipaddress:
                command = "show arp {}".format(ipaddress)
            elif interface:
                command = "show arp -if {}".format(interface)
    elif cli_type == "klish":
        if vrf == "":
            command = "show ip arp"
            if ipaddress:
                command += " {}".format(ipaddress)
            elif interface:
                intf = get_interface_number_from_name(interface)
                command += " interface {} {}".format(intf["type"],
                                                     intf["number"])
        elif vrf != "":
            command = "show ip arp vrf {}".format(vrf)
            if ipaddress:
                command += " {}".format(ipaddress)
    elif cli_type in ['rest-patch', 'rest-put']:
        output = list()
        if vrf:
            interfaces = _get_rest_l3_interfaces(dut, vrf=vrf)
        else:
            interfaces = _get_rest_l3_interfaces(dut)
        for intf in interfaces:
            output.extend(_get_rest_neighbor_entries(dut, intf))
        st.debug(output)
        if ipaddress:
            return filter_and_select(output, None, {'address': ipaddress})
        elif interface:
            return filter_and_select(output, None, {'iface': interface})
        else:
            return output
    else:
        st.error("Unsupported CLI_TYPE: {}".format(cli_type))
        return False
    return st.show(dut, command, type=cli_type)
Exemplo n.º 15
0
def set_speed(dut, data, cli_type=""):
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    cli_type = 'klish' if cli_type in ['rest-patch', 'rest-put'] else cli_type
    platform = basic.get_hwsku(dut)
    ports_per_pg = 12 if platform in ["Accton-AS7326-56X"] else 4
    non_portgroup_platforms = [
        "Accton-AS7712-32X", "Quanta-IX8A-BWDE-56X", "AS5835-54X"
    ]

    if not st.is_feature_supported("port-group", dut):
        non_portgroup_platforms.append(platform)

    ports_dict = dict()
    port_name_dict = dict()
    for index in range(0, len(data), 2):
        port = st.get_other_names(
            dut, [data[index]])[0] if "/" in data[index] else data[index]
        port_name_dict[port] = data[index + 1]
        id = re.search(r"\d+", port).group(0)
        id = (int(int(id) / ports_per_pg)) + 1
        ports_dict[str(id)] = data[index + 1]
    st.debug("port-group speed data: {}".format(ports_dict))
    commands = list()
    if cli_type == 'click':
        if platform not in non_portgroup_platforms:
            commands = [
                "config portgroup speed {} {}".format(index, speed)
                for index, speed in ports_dict.items()
            ]
        else:
            commands = [
                "portconfig -p {} -s {}".format(port, speed)
                for port, speed in port_name_dict.items()
            ]
    elif cli_type == 'klish':
        if platform not in non_portgroup_platforms:
            commands = [
                "port-group {} speed {}".format(index, speed)
                for index, speed in ports_dict.items()
            ]
        else:
            for port, speed in port_name_dict.items():
                intf_details = get_interface_number_from_name(port)
                if not intf_details:
                    st.error("Interface data not found for {} ".format(port))
                    continue
                commands.append("interface {} {}".format(
                    intf_details["type"], intf_details["number"]))
                commands.append("speed {}".format(speed))
                commands.append("exit")
    else:
        st.error("Unsupported CLI_TYPE: {}".format(cli_type))
    if commands:
        st.config(dut, commands, type=cli_type)
    return True
Exemplo n.º 16
0
def config_sag_ip(dut, **kwargs):
    '''
    Author: [email protected]
    :param dut:
    :param interface: Interface name on which SAG Gateway has to be configured.
    :param gateway: Gateway IP.
    :param mask: Mask. Default=24.
    :param config: Value can be <add|remove>.
    :param kwargs: parameters can be <interface|gateway|config|cli_type>
    :return:

    usage:
    config_sag_ip(dut1,interface='Vlan20', gateway="20.20.20.2", mask="24", config="add")
    config_sag_ip(dut1,interface='Vlan20', gateway="2002::2", mask="24", config="remove")
    '''
    ### Parameters processing
    intf = kwargs.get('interface', None)
    gateway = kwargs.get('gateway', None)
    mask = kwargs.get('mask', '24')
    config = kwargs.get('config', 'add')
    cli_type = kwargs.get('cli_type', st.get_ui_type(dut))
    cli_type = "klish" if cli_type in ["rest-put", "rest-patch"] else cli_type

    if 'interface' not in kwargs or 'gateway' not in kwargs:
        st.error("Mandatory parameters interface and gateway not found.")
        return False

    if cli_type == 'click':
        cmd = "config interface ip anycast-address {} {} {}/{}".format(
            config, intf, gateway, mask)
        output = st.config(dut, cmd)
        if "Missing argument" in output:
            st.error("Argument Missing")
            return False
        if "interface name is invalid" in output:
            st.error("Invalid peer interface")
            return False
        if "is not configured on interface" in output:
            st.error("IP is not configured")
            return False
    elif cli_type == 'klish':
        config = 'no ' if config == 'remove' else ''
        vval = get_interface_number_from_name(intf)
        cmd = "interface {} {}".format(vval['type'], vval['number'])
        type_val = 'ipv6' if ':' in gateway else 'ip'
        cmd = cmd + "\n" + "{}{} anycast-address {}/{}".format(
            config, type_val, gateway, mask)
        cmd = cmd + "\n" + "exit"
        output = st.config(dut, cmd, type="klish", conf=True)
        if "Could not connect to Management REST Server" in output:
            st.error("klish mode not working.")
            return False
    return True
Exemplo n.º 17
0
def config_port_qos_map(dut, obj_name, interface, **kwargs):
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type == 'click':
        final_data = dict()
        temp_data = dict()
        if not obj_name or not interface:
            st.log(
                "Please provide obj_name like 'AZURE' and interface like 'Ethernet0,Ethernet1'"
            )
            return False
        else:
            cos_specific_dict = {
                "tc_to_queue_map": "[TC_TO_QUEUE_MAP|" + obj_name + "]",
                "dscp_to_tc_map": "[DSCP_TO_TC_MAP|" + obj_name + "]"
            }
            temp_data[interface] = cos_specific_dict
        final_data['PORT_QOS_MAP'] = temp_data
        final_data = json.dumps(final_data)
        st.apply_json(dut, final_data)
    elif cli_type == 'klish':
        commands = list()
        intf_data = get_interface_number_from_name(interface)
        commands.append('interface {} {}'.format(intf_data['type'],
                                                 intf_data['number']))
        commands.append('qos-map tc-queue {}'.format(obj_name))
        commands.append('qos-map dscp-tc {}'.format(obj_name))
        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']:
        rest_urls = st.get_datastore(dut, 'rest_urls')
        url = rest_urls['port_qos_map_config'].format(interface)
        port_qos_map_data = {
            "openconfig-qos-maps-ext:interface-maps": {
                "config": {
                    "dscp-to-forwarding-group": obj_name,
                    "forwarding-group-to-queue": obj_name
                }
            }
        }
        if not config_rest(dut,
                           rest_url=url,
                           http_method=cli_type,
                           json_data=port_qos_map_data):
            st.error("Failed configure PORT_QOS_MAP")
            return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True
Exemplo n.º 18
0
def config_stp_interface_params(dut, iface, **kwargs):
    """

    :param dut:
    :param iface:
    :param cli_type:
    :param kwargs:
    :return:
    """
    cli_type = kwargs.setdefault('cli_type', 'click')
    del kwargs['cli_type']

    click_2_klish = {
        "root_guard": " guard root",
        "bpdu_guard": "bpduguard ",
        "portfast": "portfast",
        "uplink_fast": "uplinkfast"
    }

    if cli_type == 'click':
        for each_key in kwargs.keys():
            if each_key == "priority" or each_key == "cost":
                command = "config spanning_tree interface {} {} {}".format(
                    each_key, iface, kwargs[each_key])
            elif each_key == "bpdu_guard_action":
                command = "config spanning_tree interface bpdu_guard enable {} {}".format(
                    iface, kwargs[each_key])
            else:
                command = "config spanning_tree interface {} {} {}".format(
                    each_key, kwargs[each_key], iface)
            st.config(dut, command)

    elif cli_type == 'klish':
        interface_data = utils.get_interface_number_from_name(iface)
        command = [
            'interface {} {}'.format(interface_data["type"],
                                     interface_data["number"])
        ]
        for each_key in kwargs.keys():
            no_form = 'no' if kwargs[each_key] == 'disable' else ''
            if each_key == "priority" or each_key == "cost":
                command.append('spanning-tree {} {}'.format(
                    each_key, kwargs[each_key]))
            elif each_key == "bpdu_guard_action":
                command.append(
                    '{} spanning-tree bpduguard port-shutdown'.format(no_form))
            else:
                command.append("{} spanning-tree {}".format(
                    no_form, click_2_klish[each_key]))
        command.append('exit')
        st.config(dut, command, type=cli_type)
Exemplo n.º 19
0
def clear_interface_counters(dut, **kwargs):
    cli_type = st.get_ui_type(dut, **kwargs)
    interface_name = kwargs.get("interface_name", "")
    interface_type = kwargs.get("interface_type", "all")
    if cli_type == "klish":
        confirm = kwargs.get("confirm") if kwargs.get("confirm") else "y"
        if interface_type != "all":
            interface_type = get_interface_number_from_name(
                str(interface_name))
            if interface_type["type"] and interface_type["number"]:
                interface_val = "{} {}".format(interface_type.get("type"),
                                               interface_type.get("number"))
            else:
                interface_val = ""
        else:
            interface_val = "all"
        if not interface_val:
            st.log("Invalid interface type")
            return False
        command = "clear counters interface {}".format(interface_val)
        st.config(dut,
                  command,
                  type=cli_type,
                  confirm=confirm,
                  conf=False,
                  skip_error_check=True)
    elif cli_type == "click":
        command = "show interfaces counters -c"
        if not st.is_feature_supported(
                "show-interfaces-counters-clear-command", dut):
            st.community_unsupported(command, dut)
            return st.config(dut, "sonic-clear counters")
        return st.show(dut, command)
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['clear_interface_counters']
        clear_type = 'all' if interface_type == 'all' else interface_name
        clear_counters = {
            "sonic-interface:input": {
                "interface-param": clear_type
            }
        }
        if not config_rest(
                dut, http_method='post', rest_url=url,
                json_data=clear_counters):
            st.error("Failed to clear interface counters")
            return False
    else:
        st.log("Unsupported CLI TYPE {}".format(cli_type))
        return False
    return True
Exemplo n.º 20
0
def show(dut, interface_name=None, stc_type=None, **kwargs):
    """
        API to show storm control configuration
        Author : Chaitanya Vella ([email protected])
        :param dut:
        :param interface_name:
        :param stc_type:
        :param bits_per_sec:
        :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    interface_data = utils.get_interface_number_from_name(interface_name)
    if cli_type == 'click':
        if not interface_name:
            command = "show storm-control all"
        else:
            command = "show storm-control interface {}".format(interface_name)
        return st.show(dut, command, type=cli_type)
    elif cli_type == 'klish':
        if not interface_name:
            command = "show storm-control"
        else:
            command = "show storm-control interface {} {}".format(
                interface_data["type"], interface_data["number"])
        return st.show(dut, command, type=cli_type)
    elif cli_type in ['rest-put', 'rest-patch']:
        rest_urls = st.get_datastore(dut, "rest_urls")
        if stc_type == "unknown-multicast":
            stc_type = "unknown_multicast"
        if stc_type == "unknown-unicast":
            stc_type = "unknown_unicast"
        url = rest_urls['config_stormcontrol'].format(interface_name,
                                                      stc_type.upper())
        rest_get_output = get_rest(dut, rest_url=url)
        actual_data = rest_get_output['output'][
            'openconfig-if-ethernet-ext:config']
        temp = {}
        output = []
        temp['interface'] = actual_data['ifname']
        temp['rate'] = actual_data['kbps']
        stc_type = (actual_data['storm-type'].lower())
        if stc_type == "unknown_multicast":
            stc_type = "unknown-multicast"
        if stc_type == "unknown_unicast":
            stc_type = "unknown-unicast"
        temp['type'] = str(stc_type)
        output.append(temp)
        return output
    else:
        st.log("invalid cli type")
        return False
Exemplo n.º 21
0
def config_interfaces(dut, domain_id, interface_list, **kwargs):
    '''
    Author: [email protected]
    :param dut:
    :param domain_id: Mclag domain_id
    :param interface_list: list of mclag interfaces (portchannels) in the dut for the given domain
    :param kwargs: optional parameters can be <config|cli_type>
    :return:

    usage:
    config_mclag_interface(dut1,10,['PortChannel001','PortChannel002'])
    config_mclag_interface(dut1,10,['PortChannel001','PortChannel002'],config='del')
    '''
    ### Optional parameters processing
    config = kwargs.get('config', 'add')
    cli_type = kwargs.get('cli_type', st.get_ui_type(dut, **kwargs))
    cli_type = "klish" if cli_type in ["rest-put", "rest-patch"] else cli_type

    if not interface_list:
        st.error("interfaces not found for  Mclag interface configuration")
        return False
    interface_list = interface_list if isinstance(interface_list,
                                                  list) else [interface_list]

    if cli_type == 'click':
        cmd = "config mclag member {} {} ".format(config, domain_id)
        for intf in interface_list:
            cmd += '{},'.format(intf)
        cmd = cmd.strip(',')
        output = st.config(dut, cmd)
        if "Domain doesn't exist" in output:
            st.error(" Mclag domain:{} doesn't exist".format(domain_id))
            return False
        if "name should have prefix 'PortChannel' " in output:
            st.error(" Mclag interface has to be PortChannel")
            return False
    elif cli_type == 'klish':
        cmd = ''
        config = 'no ' if config == 'del' else ''
        for intf in interface_list:
            pintf = get_interface_number_from_name(intf)
            cmd = cmd + "\n" + "interface {} {}".format(
                pintf['type'], pintf['number'])
            cmd = cmd + "\n" + "{}mclag {}".format(config, domain_id)
            cmd = cmd + "\n" + "exit"
        output = st.config(dut, cmd, type="klish", conf=True)
        if "Could not connect to Management REST Server" in output:
            st.error("klish mode not working.")
            return False
    return True
Exemplo n.º 22
0
def test_ft_snmp_dot1q_tp_fdb_port():
    """
    Author : Prasad Darnasi<*****@*****.**>
    Verify that the dot1qTpFdbPort Object functions properly.
    Reference Test Bed : D1 --- Mgmt Network
    """
    get_snmp_output = snmp_obj.walk_snmp_operation(
        ipaddress=ipaddress,
        oid=data.oid_dot1q_Tp_Fdb_Port,
        community_name=data.ro_community)
    intf_name = util_obj.get_interface_number_from_name(vars.D1T1P2)
    if intf_name.get('number') not in get_snmp_output[0]:
        st.report_fail("snmp_output_failed", "dot1qTpFdbPort")
    st.report_pass("test_case_passed")
Exemplo n.º 23
0
def get_mac(dut, **kwargs):
    """
    :param dut:
    :type dut:
    :return:
    :rtype:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type == "click":
        return st.show(dut, "show mac")
    elif cli_type == "klish":
        response = dict()
        attrs = ["address", "interface", "type", "vlan", "count"]
        command = "show mac address-table"
        if kwargs.get("count"):
            command += " count"
            output = st.show(dut, command, type=cli_type)
            if output:
                for data in output:
                    for key, value in data.items():
                        if value:
                            response[key] = value
            return response
        else:
            for attr in attrs:
                if kwargs.get(attr):
                    if attr not in ["type", "count"]:
                        if attr == "interface":
                            interface_number = get_interface_number_from_name(
                                kwargs.get(attr))
                            if interface_number:
                                command += " {} {} {}".format(
                                    attr, interface_number["type"],
                                    interface_number["number"])
                        else:
                            command += " {} {}".format(attr, kwargs.get(attr))
                    else:
                        command += " {}".format(kwargs.get(attr))
            return st.show(dut, command, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        network_instance_name = 'default'
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['all_mac_entries'].format(network_instance_name)
        output = get_rest(dut, rest_url=url)
        rest_get_output = processed_output_based_macentries(output)
        return rest_get_output
    else:
        st.log("Invalid cli type")
        return False
Exemplo n.º 24
0
def config_bpdu_filter(dut, **kwargs):
    """
    API to config BPDU filter for global and interface level
    Usage:
    ======
    Interface level config:
    =========================
    config_bpdu_filter(dut, interface="Ethernet8", action="enable", cli_type="klish")
    config_bpdu_filter(dut, interface="Ethernet8", no_form=True, cli_type="klish")

    Global level config:
    ====================
    config_bpdu_filter(dut, cli_type="klish")
    config_bpdu_filter(dut, ,no_form=True, cli_type="klish")

    :param dut:
    :param kwargs:
    :return:
    """
    cli_type = kwargs.get("cli_type", "klish")
    interface = kwargs.get("interface", None)
    no_form = kwargs.get("no_form", None)
    action = kwargs.get("action", "enable")
    commands = list()
    if not interface:
        command = "spanning-tree edge-port bpdufilter default"
        if no_form:
            command = "no {}".format(command)
        commands.append(command)
    else:
        interface_details = utils.get_interface_number_from_name(interface)
        if not interface_details:
            st.log("Interface details not found {}".format(interface_details))
            return False
        commands.append("interface {} {}".format(
            interface_details.get("type"), interface_details.get("number")))
        command = "spanning-tree bpdufilter"
        if no_form:
            command = "no {}".format(command)
        elif action:
            command = "{} {}".format(command, action)
        else:
            command = ""
        if command:
            commands.append(command)
    if commands:
        st.config(dut, commands, type=cli_type)
        return True
    return False
Exemplo n.º 25
0
def get_arp_count(dut, ipaddress=None, interface=None, cli_type="", **kwargs):
    """
    To get arp count
    Author: Prudvi Mangadu ([email protected])
    :param dut:
    :param ipaddress:
    :param interface:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if cli_type == "click":
        command = "show arp"
        if ipaddress:
            command += " {}".format(ipaddress)
        if interface:
            command += " -if {}".format(interface)
        command += " | grep 'Total number of entries'"
    elif cli_type == "klish":
        command = "show ip arp"
        if interface:
            intf = get_interface_number_from_name(interface)
            command += " interface {} {}".format(intf["type"], intf["number"])
        if 'vrf' in kwargs:
            command += " vrf {}".format(kwargs["vrf"])
        if ipaddress:
            st.log("Unsupported attribute ipaddress")
            return 0
        command += " summary"
    elif cli_type in ["rest-patch", "rest-put"]:
        show_arp(dut, ipaddress=None, interface=None, vrf="", cli_type="")
        if interface:
            out = show_arp(dut, interface=interface, cli_type=cli_type)
        if 'vrf' in kwargs:
            out = show_arp(dut, vrf=kwargs['vrf'], cli_type=cli_type)
        if ipaddress:
            out = show_arp(dut, ipaddress=ipaddress, cli_type=cli_type)
        if not (interface and kwargs.get('vrf') and ipaddress):
            out = show_arp(dut, cli_type=cli_type)
        return len(out)
    else:
        st.error("Unsupported CLI_TYPE: {}".format(cli_type))
        return False
    output = st.show(dut, command, type=cli_type)
    out = dicts_list_values(output, 'count')
    return int(out[0]) if out else 0
Exemplo n.º 26
0
def config_access_group(dut, **kwargs):
    """
    API to map interface to Access-list
    Author : Pradeep Bathula ([email protected])
    :param dut:
    :type dut:
    :param cli_type:
    :type cli_type:klish
    :param table_name:
    :type table_name:
    :param port:
    :type interface:
    :param access_group_action:
    :type access_group_action:in|out
    :return:
    """
    cli_type = kwargs.get("cli_type", "klish")
    table_name = kwargs.get("table_name", None)
    port = kwargs.get("port", None)
    access_group_action = kwargs.get("access_group_action", None)
    skip_error_check = kwargs.get("skip_error_check", True)
    config = kwargs.get("config", "yes")
    mode = "" if config == "yes" else "no "

    st.log("Assigning Access-group action on interface")
    if not cli_type == "klish":
        st.log("Unsupported CLI type {} provided, required klish".format(
            cli_type))
        return False
    if not (table_name and port and access_group_action and config):
        st.log(
            "Mandatory parameters like table_name and/or port and/or access_group_action and/or config not passed"
        )
        return False
    interface_details = util_obj.get_interface_number_from_name(port)
    commands = list()
    commands.append("interface {} {}".format(interface_details.get("type"),
                                             interface_details.get("number")))
    commands.append("{}ip access-group {} {}".format(mode, table_name,
                                                     access_group_action))
    commands.append("exit")
    st.config(dut, commands, type=cli_type, skip_error_check=skip_error_check)
    return True
Exemplo n.º 27
0
def show_interface_transceiver(dut, mode, interface=None, cli_type=""):
    """
    API to get the interface transceiver eeprom details
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :param mode: eeprom , presence
    :param interface:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if mode not in ["eeprom", "presence"]:
        st.log("Unsupported modes provided ...")
        return False
    if cli_type == "click":
        command = "show interface transceiver {}".format(mode)
        if interface:
            command = "show interface transceiver {} | grep -w {}".format(mode, interface)
        return st.show(dut, command)
    elif cli_type == "klish":
        if interface:
            intf_data = utils.get_interface_number_from_name(interface)
            command = "show interface transceiver {} {}".format(intf_data['type'], intf_data['number'])
        else:
            command = "show interface transceiver"
        output = st.show(dut, command, type=cli_type)
        for i in range(len(output)):
            if output[i]['presence'] == "PRESENT":
                output[i]['presence'] = "Present"
                output[i]['eeprom_status'] = "SFP EEPROM detected"
            else:
                output[i]['presence'] = "Not present"
                output[i]['eeprom_status'] = "SFP EEPROM Not detected"
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url1 = rest_urls['get_fan_psu']
        data = get_rest(dut, rest_url=url1)["output"]
        output = _get_transceiver_data(data)
        if interface:
            output = filter_and_select(output, match={"port": interface})
    else:
        st.error("Unsupported CLI Type provided: {}".format(cli_type))
        return []
    return output
Exemplo n.º 28
0
def config_intf_diagnostics(dut, intf, mode, **kwargs):
    '''
    :param dut:
    :param intf:
    :param feature:
        value: loopback (default)
    :param mode:
        value: <media-side-output|media-side-input|host-side-output|host-side-input>
    :param action:
        value: <enable|disable>, default is enable
    :param skip_error:
    :return:

    :mode
    :
    import apis.system.cmis as cmis_api
    cmis_api.config_intf_diagnostics(dut=data.dut1, intf='Ethernet17', mode='media-side-input')
    cmis_api.config_intf_diagnostics(dut=data.dut1, intf='Ethernet17', mode='media-side-input',action='disable')
    '''

    st.log(
        'API: config_intf_diagnostics - DUT: {}, intf: {}, mode: {}, kwargs: {}'
        .format(dut, intf, mode, kwargs))

    feature = kwargs.get('feature', 'loopback')
    action = kwargs.get('action', 'enable')
    skip_error = kwargs.get('skip_error', False)
    #cli_type = kwargs.pop('cli_type', st.get_ui_type(dut,**kwargs))

    intf_info = get_interface_number_from_name(intf)
    cmd = 'interface diagnostics {} {} {} {} {}'.format(
        feature, intf_info['type'], intf_info['number'], mode, action)
    try:
        st.config(dut,
                  cmd,
                  skip_error_check=skip_error,
                  type="klish",
                  conf=True)
    except Exception as e:
        st.log(e)
        return False
    return True
Exemplo n.º 29
0
def config_uniqueip(dut, skip_error=False, **kwargs):
    '''
    Configures< unique-ip add | del> vlan for Mclag
    Author: [email protected]
    :param dut:
    :param kwargs: optional parameters can be <op_type|vlan|cli_type>
    :return:

    Usage:
    config_uniqueip(dut1, op_type='add', vlan='Vlan10')
    config_uniqueip(dut1, op_type='del', vlan='Vlan10')
    '''
    ### Optional parameters processing
    type_val = kwargs.get('op_type', None)
    vlan_val = kwargs.get('vlan', None)
    cli_type = kwargs.get('cli_type', st.get_ui_type(dut, **kwargs))

    if cli_type == 'click':
        cmd = ""
        if 'op_type' in kwargs and 'vlan' in kwargs:
            cmd += "config mclag unique-ip {} {}\n".format(type_val, vlan_val)
        output = st.config(dut, cmd)
        if "configure mclag domain first" in output:
            st.error("Domain_id doesn't exist")
            return False
    elif cli_type == 'klish':
        if 'op_type' in kwargs and 'vlan' in kwargs:
            vval = get_interface_number_from_name(vlan_val)
            cmd = "interface {} {}".format(vval['type'], vval['number'])
            type_val = 'no ' if type_val == 'del' else ''
            cmd = cmd + "\n" + "{}mclag-separate-ip".format(type_val)
            cmd = cmd + "\n" + "exit"
        output = st.config(dut,
                           cmd,
                           type="klish",
                           conf=True,
                           skip_error_check=skip_error)
        if "Could not connect to Management REST Server" in output:
            st.error("klish mode not working.")
            return False
    return True
Exemplo n.º 30
0
def bind_qos_map(dut, intf_name,config="yes",**kwargs):
    """
    purpose:
            This definition is used to bind QOS map to an interface

    Arguments:
    :param dut: device to be configured
    :type dut: string
    :param intf_name: interface name to be binded with qos map
    :type intf_name: string
    :param config: whether to configure or delete
    :type config: string
    :param map_type: qos map type like dscp-tc, dot1p-tc etc
    :type map_type: string
    :param map_name: qos map name
    :type map_name: string
    :return: None/False; False for unsupported UI type

    usage:
          bind_qos_map(dut1,"Ethernet15",map_type="dscp-tc",map_name="dscpToTc")
          bind_qos_map(dut1,"PortChannel12",map_type="dscp-tc",map_name="dscpToTc")
          bind_qos_map(dut1,"PortChannel12",config="no",map_type="dscp-tc")
    Created by: Julius <[email protected]
    """

    cli_type = st.get_ui_type(dut, **kwargs)
    cli_type = "klish" if cli_type in ["rest-put", "rest-patch"] else cli_type
    if cli_type == "klish":
        intf_details = get_interface_number_from_name(intf_name)
        cmd = "interface {} {} \n".format(intf_details["type"],intf_details["number"])
        if config.lower() == "yes":
            if "map_type" in kwargs and "map_name" in kwargs:
                cmd += "qos-map {} {} \n".format(kwargs["map_type"],kwargs["map_name"])
        else:
            if "map_type" in kwargs:
                cmd += "no qos-map {} \n".format(kwargs["map_type"])
        cmd += "exit"
    else:
        st.log("support for UI type {} yet to be added".format(cli_type))
        return False
    return st.config(dut, cmd, type=cli_type)