Example #1
0
def _get_entries_with_native_port(dut, output, **kwargs):
    cli_type = st.get_ui_type(dut, **kwargs)
    ifname_type = kwargs.get("ifname_type", "")
    verify_ifname_type(dut, mode='standard')
    st.log("OUTPUT:{}".format(output))
    for entry in output:
        if (cli_type == 'klish' and ifname_type == "alias"):
            st.log("Interface : {}".format(st.get_other_names(dut, [entry['interface']])[0]))
        else:
            st.log("Else Interface : {}".format(entry.get('interface')))
        entry.update(interface=st.get_other_names(dut, [entry['interface']])[0] if (cli_type == 'klish' and ifname_type == "alias") else entry.get('interface'))
    st.log("OUTPUT1:{}".format(output))
    return output
Example #2
0
def get_params():
    pddf_data.base_mac_address = baapi.get_ifconfig_ether(vars.D1, "eth0")
    pddf_data.platform_name_summary = baapi.get_platform_summary(vars.D1)
    pddf_data.platform_hwsku = pddf_data.platform_name_summary["hwsku"].lower()
    platform_check()
    pddf_data.platform_name = pddf_data.platform_name_summary["platform"]
    pddf_data.serial_number = baapi.show_version(vars.D1)['serial_number']
    pddf_data.platform_constants = st.get_datastore(vars.D1, "constants",
                                                    pddf_data.platform_hwsku)
    pddf_data.fan_list = pddf_data.platform_constants.get(
        "PDDF_FANS_LIST", None)
    pddf_data.psu_list = pddf_data.platform_constants.get(
        "PDDF_PSU_LIST", None)
    pddf_data.thermal_list = pddf_data.platform_constants.get(
        "PDDF_THERMAL_LIST", None)
    pddf_data.manufacturer = pddf_data.platform_constants.get(
        "Manufacturer", None)
    if not all([
            pddf_data.fan_list, pddf_data.psu_list, pddf_data.thermal_list,
            pddf_data.manufacturer
    ]):
        st.report_env_fail("pddf_get_constanc_fail", pddf_data.feature,
                           pddf_data.platform_hwsku)
    pddf_data.up_port_list = intapi.get_up_interfaces(vars.D1)
    if not pddf_data.up_port_list:
        st.report_env_fail("up_interface_not_found", pddf_data.feature)
    pddf_data.up_port = get_sfpytils_supported_up_interface()
    if any("/" in interface
           for interface in make_list(pddf_data.up_port_list)):
        pddf_data.up_port_list = st.get_other_names(
            vars.D1, make_list(pddf_data.up_port_list))
        pddf_data.alias_up_port = st.get_other_names(
            vars.D1, make_list(pddf_data.up_port))[0]
    else:
        pddf_data.alias_up_port = pddf_data.up_port
    #Removed Warm reboot as it's not supported in Buzznik+
    pddf_data.reboot_cause_dict = {
        'warm': 'warm-reboot',
        'fast': 'fast-reboot',
        'normal': "issued 'reboot'"
    }
    pddf_data.reboot_type = random.sample(pddf_data.reboot_cause_dict.keys(),
                                          k=1)[0]
    if pddf_data.platform_hwsku not in pddf_data.hw_constants[
            'WARM_REBOOT_SUPPORTED_PLATFORMS']:
        pddf_data.reboot_cause_dict.pop('warm')
        pddf_data.reboot_type = random.sample(
            pddf_data.reboot_cause_dict.keys(), k=1)[0]
Example #3
0
def dhcp_client_start(dut, interface, family="ipv4", run_bckgrnd=False):
    """
    API to start DHCLIENT in foreground for v4 and background for v6
    Author Chaitanya Vella ([email protected])
    :param dut:
    :type dut:
    :param portlist:
    :type portlist:
    """
    if interface != None:
        if '/' in interface:
            interface = st.get_other_names(dut,[interface])[0]

    v6_opt = "" if family == "ipv4" else "-6"
    run_bckgrnd = True if (family == "ipv6" or run_bckgrnd) else False
    bckgrd = "&" if run_bckgrnd else ""
    command = "dhclient {} {} {}".format(v6_opt, interface, bckgrd)
    output = st.config(dut, command, skip_error_check=True)
    if bckgrd:
        output = remove_last_line_from_string(output)
        if output:
            return output.split(" ")[1]
        else:
            return None
    else:
        return True
Example #4
0
def udld_block(dut, **kwargs):
    """
    Author: [email protected]
    udld_blockf(dut=data.dut1,intf ='Ethernet10')

    Block the UDLD packtets at interface level
    :param dut:
    :param intf:
    :return:
    """
    if 'config' in kwargs:
        config = kwargs['config']
    else:
        config = 'yes'

    if config.lower() == 'yes':
        config_cmd = 'enable'
    else:
        config_cmd = 'disable'

    if 'intf' in kwargs:
        if type(kwargs['intf']) is list:
            kwargs['intf'] = list(kwargs['intf'])
        else:
            kwargs['intf'] = [kwargs['intf']]
        my_cmd = ''
        for intf in kwargs['intf']:
            if '/' in intf:
                intf = st.get_other_names(dut, [intf])[0]
            my_cmd += 'udldctl rx_drop {} {}\n'.format(config_cmd, intf)
    else:
        st.error("Mandatory argument interface name Not Found")
        return False
    st.config(dut, my_cmd, type="click")
Example #5
0
def get_intf_pmap(dut, interface_name=None):
    """
    Author: Chaitanya Vella ([email protected])
    This API is used to get the interface pmap details
    :param dut: dut
    :param interface_name: List of interface names
    :return:
    """
    import apis.system.interface as interface_obj
    ##Passing the cli_type as click in the API call "interface_status_show" because the lanes information is available only in click CLI.
    ##Please refer the JIRA: SONIC-22102 for more information.
    interfaces = cutils.make_list(interface_name) if interface_name else ''
    if interfaces:
        if any("/" in interface for interface in interfaces):
            interfaces = st.get_other_names(dut, interfaces)
            key = 'alias'
        else:
            key = 'interface'
        st.debug("The interfaces list is: {}".format(interfaces))
        interface_list = interface_obj.interface_status_show(
            dut, interfaces=interfaces, cli_type='click')
    else:
        key = 'alias' if interface_obj.show_ifname_type(
            dut, cli_type='klish') else 'interface'
        interface_list = interface_obj.interface_status_show(dut,
                                                             cli_type='click')
    interface_pmap = dict()
    pmap_list = get_pmap(dut)
    for detail in cutils.iterable(interface_list):
        lane = detail["lanes"].split(
            ",")[0] if "," in detail["lanes"] else detail["lanes"]
        for pmap in pmap_list:
            if pmap["physical"] == lane:
                interface_pmap[detail[key]] = pmap["interface"]
    return interface_pmap
Example #6
0
def check_ports_from_rest_output(resp, threshold_type, buffer_type, dut_ports):
    if any("/" in interface for interface in make_list(dut_ports)):
        dut_ports = st.get_other_names(vars.D1, make_list(dut_ports))
    result = True
    if threshold_type == 'priority-group' and buffer_type in [
            'shared', 'headroom'
    ]:
        rest_ports = [each['port'] for each in resp['report'][0]['data']]

    elif threshold_type == 'queue' and buffer_type in ['unicast', 'multicast']:
        rest_ports = list(set([each[1] for each in resp['report'][0]['data']]))
    else:
        st.error('No Match for threshold_type and buffer_type found')
        return None

    for each in dut_ports:
        if each not in rest_ports:
            st.error(
                ">>> Port '{}' information is *not* available in REST data of {} {}"
                .format(each, threshold_type, buffer_type))
            result = False
        else:
            st.debug(
                "Port '{}' information is available in REST data".format(each))
    return result
Example #7
0
def get_interface_breakout_mode(dut, interface, *fields):

    """
    Author: Naveen Nag
    email : [email protected]
    :param dut:
    :param interface:
    :param fields:
    :return: port,interface,supported_modes,default mode

    Usage:
    port.get_interface_breakout_mode(dut1, 'Ethernet4', 'port','supported_modes')
    :return  - [{'supported_modes': '1x100G[40G], 4x25G[10G]', 'port': '1/2'}]

    """
    if '/' not in interface:
        temp_vars = st.get_testbed_vars()
        if temp_vars.config.ifname_type == 'alias':
            interface = st.get_other_names(dut,[interface])[0]
    if '/' in interface:
        interface = '/'.join([interface.split('/')[0], interface.split('/')[1]])
    output = st.show(dut, "show interface breakout modes | grep \"{} \"".format(interface), type='klish')
    entries = filter_and_select(output, fields, {'iface': interface})
    if entries:
        return entries
    else:
        st.error("{} is not part of the output".format(interface))
        return False
Example #8
0
def get_threshold_from_rest_output(resp, threshold_type, buffer_type,
                                   port_alias, index):
    if any("/" in interface for interface in make_list(port_alias)):
        port_alias = st.get_other_names(vars.D1, make_list(port_alias))[0]
    st.log(resp)
    if threshold_type == 'priority-group' and buffer_type == 'shared':
        for each in resp['report'][0]['data']:
            if port_alias in each['port']:
                return each['data'][index][1]
    elif threshold_type == 'priority-group' and buffer_type == 'headroom':
        for each in resp['report'][0]['data']:
            if port_alias in each['port']:
                return each['data'][index][2]
    elif threshold_type == 'queue' and buffer_type == 'multicast' and port_alias == 'CPU':
        for each in resp['report'][0]['data']:
            if each[0] == index:
                return each[1]
    elif threshold_type == 'queue' and buffer_type in ['unicast', 'multicast']:
        for each in resp['report'][0]['data']:
            if each[1] == port_alias and each[2] == index:
                return each[3]
    else:
        st.error('No Match for threshold_type and buffer_type found')
    st.error("No Value found for Port:{} Index:{} in the rest data".format(
        port_alias, index))
    return None
Example #9
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
Example #10
0
def get_sfpytils_supported_up_interface():
    """
    This function return the First UP interface which supports SFP utils.
    :return:
    """
    out = bsapi.show_sfputil(vars.D1, 'lpmode')
    for port in pddf_data.up_port_list:
        if "/" in port:
            port = st.get_other_names(vars.D1, make_list(port))[0]
        if filter_and_select(out, None, {'port': port}):
            return port
Example #11
0
def fill_dev_ids():
    dids, palias = {}, {}
    for dut in st.get_dut_names():
        dids[dut] = st.get_device_alias(dut, True, True)
        palias[dut] = {}
        links = st.get_dut_links_local(dut)
        onames = st.get_other_names(dut, links)
        for index, local in enumerate(links):
            palias[dut][local] = onames[index]
    for tg in st.get_tg_names():
        dids[tg] = st.get_device_alias(tg, True, True)
    return dids, palias
Example #12
0
def initialize_variables():
    global data
    data = SpyTestDict()
    data.session_name = "Mirror_Ses"
    data.gre_type = "0x88ee"
    data.dscp = "50"
    data.ttl = "100"
    data.queue = "0"
    data.type = 'monitoring'
    data.source_ip = '11.1.1.2'
    data.destination_ip = '15.1.1.2'
    data.source_mac = "00:00:02:00:00:01"
    data.destination_mac = "00:00:01:00:00:01"
    data.mode_high = 'high'
    data.mode_low = 'low'
    data.polling_interval = '1'
    data.threshold_percentage_type = 'percentage'
    data.threshold_used_type = 'used'
    data.threshold_free_type = 'free'
    data.ipv4_route_family = "ipv4_route"
    data.ipv6_route_family = "ipv6_route"
    data.fdb_family = "fdb"
    data.ipv4_neighbor_family = "ipv4_neighbor"
    data.ipv6_neighbor_family = "ipv6_neighbor"
    data.acl_group_entry_family = 'acl_group_entry'
    data.acl_group_counter_family = 'acl_group_counter'
    data.ipv6_nexthop_family = 'ipv6_nexthop'
    data.ipv4_nexthop_family = 'ipv4_nexthop'
    data.acl_table_family = "acl_table"
    data.mode_high_percentage = 50
    data.mode_low_percentage = 20
    data.mode_high_used = 1000
    data.mode_low_used = 10
    data.mode_high_free = 1000
    data.mode_low_free = 10
    data.mtu = "9216"
    data.eth = data.eth_name = st.get_free_ports(vars.D1)[0]
    if any("/" in interface for interface in make_list(data.eth_name)):
        data.eth_name = st.get_other_names(vars.D1, make_list(data.eth))[0]
    data.property = "mtu"
    data.mtu_default = "9100"
    data.portchannel_name = "PortChannel7"
    data.members_dut1 = [vars.D1D2P1, vars.D1D2P2]
    data.members_dut2 = [vars.D2D1P1, vars.D2D1P2]
    data.session_name_port = "Mirror1"
    data.mirror_type = "span"
    data.mirror_interface = vars.D1T1P2
    data.source_interface = vars.D1T1P1
    data.direction_list = "rx"
Example #13
0
def verify_error_db_redis(dut, table, **kwargs):
    """
    Verify error db using redis cli
    Author : Prudvi Mangadu ([email protected])
    :param :dut:
    :param :table:
    :param :route:
    :param :mask:
    :param :ifname:
    :param :nhp:
    :param :operation:
    :param :rc:
    :param :result: (Default True)
    :param :iteration: default(30)
    :return:
    """
    port = kwargs.pop("ifname")
    port = st.get_other_names(dut, [port])[0] if "/" in port else port
    exp_result = kwargs.get("result", True)
    iteration = kwargs.get("iteration", 30)
    command = ''
    if table == "ERROR_ROUTE_TABLE":
        command = redis.build(
            dut, redis.ERROR_DB,
            "hgetall {}:{}/{}".format(table, kwargs.pop("route"),
                                      kwargs.pop("mask")))
    elif table == "ERROR_NEIGH_TABLE":
        command = redis.build(
            dut, redis.ERROR_DB,
            "hgetall {}:{}:{}".format(table, port, kwargs.pop("nhp")))
    else:
        st.error("Invalid table name - {}".format(table))

    i = 1
    while True:
        output = st.show(dut, command)
        st.debug(output)
        result = True
        for each in kwargs.keys():
            if not filter_and_select(output, None, {each: kwargs[each]}):
                st.error("No match for {} = {} in redis cli".format(
                    each, kwargs[each]))
                result = False
        if result == exp_result:
            return True
        if i >= iteration:
            return False
        i += 1
        st.wait(1)
Example #14
0
def verify_show_error_db_multi(dut, table, *argv, **kwargs):
    """
    Verify multiple Error Database entries.
    Author : Prudvi Mangadu ([email protected])
    :param : dut:
    :param : table:
    :param : result: Expected result(Default True)
    :param : iteration: default(30)
    :param : argv: list  of dict arguments to verify
    :return:
    """
    exp_result = kwargs.get("result", True)
    iteration = kwargs.get("iteration", 30)
    cli_type = st.get_ui_type(dut, **kwargs)
    if kwargs.get("interface"):
        intf_entry_val = kwargs.get("interface")
        if cli_type == "klish":
            if vars.config.ifname_type == "alias":
                intf_entry_val = st.get_other_names(
                    vars.D1, [kwargs.get("interface")])[0]
        kwargs.update({"interface": intf_entry_val})
    command = "show error_database"
    if table:
        command = "show error_database {}".format(table)
    i = 1
    while True:
        output = st.show(dut, command)
        output = _get_entries_with_native_port(dut, output, **kwargs)
        st.debug(output)
        result = True
        for each_row in argv:
            row_match = filter_and_select(output, None, each_row)
            if not row_match:
                st.log("Entry not found - {}".format(', '.join(
                    ["{}='{}'".format(k, each_row[k]) for k in each_row])))
                result = False
            else:
                st.log("Entry found - {}".format(', '.join(
                    ["{}='{}'".format(k, each_row[k]) for k in each_row])))
        if result == exp_result:
            return True
        if i >= iteration:
            return False
        i += 1
        st.wait(1)
Example #15
0
def get_sbin_intf_mac(dut, interface=None):
    """
    This proc is to return the mac address of the interface from the ifconfig o/p.
    :param dut: DUT Number
    :param interface: Interface number
    :return:
    """
    if st.get_args("filemode"):
        return "00:00:ba:db:ad:ba"

    interface = interface or st.get_mgmt_ifname(dut)
    if '/' in interface:
        interface = st.get_other_names(dut, [interface])[0]
    my_cmd = "/sbin/ifconfig {}".format(interface)
    output = st.show(dut, my_cmd)
    output = dict(output[0])
    mac = output['mac']
    return mac
Example #16
0
def dhcp_client_stop(dut, interface, pid=None, family="ipv4", skip_error_check=False, show_interface=False):
    """
    API to stop DHCP client either by using process id or dhclient
    Author Chaitanya Vella ([email protected])
    :param dut:
    :type dut:
    :param portlist:
    :type portlist:
    """
    if interface != None:
        if '/' in interface:
            interface = st.get_other_names(dut,[interface])[0]

    v6_opt = "" if family == "ipv4" else "-6"
    command = "kill -9 {}".format(pid) if pid else  "dhclient {} -r {}".format(v6_opt, interface)
    st.config(dut, command, skip_error_check=skip_error_check)
    if show_interface:
        get_interface_ip_address(dut, interface_name=interface, family=family)
    return True
Example #17
0
def udld_clear_stats_intf(dut, **kwargs):
    """
    Author: [email protected]
    udld_clear_stats_intf(dut=data.dut1,intf ='Ethernet10')

    Reset the UDLD stats at interface level
    :param dut:
    :param intf:
    :return:
    """
    if 'intf' in kwargs:
        if type(kwargs['intf']) is list:
            kwargs['intf'] = list(kwargs['intf'])
        else:
            kwargs['intf'] = [kwargs['intf']]
    my_cmd = ''
    for intf in kwargs['intf']:
        if '/' in intf:
            intf = st.get_other_names(dut, [intf])[0]
        my_cmd += 'clear udld statistics {}\n'.format(intf)
    st.config(dut, my_cmd, type="click")
Example #18
0
def show(dut, *argv, **kwargs):
    """
    show commands summary
    Author: prudviraj k ([email protected])
    :param dut:
    :param argv:
    :param interval:
    :param clear_interval:
    :param persistent_head:
    :param persistent_shared:
    :param threshold_head:
    :param threshold__shared:
    :param watermark_head:
    :param watermark_shared:
    :param port_alias:
    :param column_name:
    :param queue_value:
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type in ["rest-patch", "rest-put"] and 'column_name' in kwargs:
        cli_type = 'klish'
    if cli_type in ["rest-patch", "rest-put"]:
        for queue_type in argv:
            if queue_type in [
                    "buffer_pool_watermark",
                    "buffer_pool_persistent-watermark",
                    "buffer_pool_counters_DB"
            ]:
                cli_type = 'klish'
    persistent = "show priority-group persistent-watermark"
    user_watermark = "show priority-group watermark"
    queue_user_watermark = "show queue watermark"
    queue_persistent_watermark = "show queue persistent-watermark"
    if cli_type == 'click' or cli_type == 'klish':
        if "snapshot_interval" in argv:
            command = "show watermark interval"
        elif 'telemetry_interval' in argv:
            command = "show watermark telemetry interval"
        elif 'persistent_PG_headroom' in argv:
            command = persistent + " " + "{}".format("headroom")
        elif 'persistent_PG_shared' in argv:
            command = persistent + " " + "{}".format("shared")
        elif 'user_watermark_PG_headroom' in argv:
            command = user_watermark + " " + "{}".format("headroom")
        elif 'user_watermark_PG_shared' in argv:
            command = user_watermark + " " + "{}".format("shared")
        elif 'queue_user_watermark_unicast' in argv:
            command = queue_user_watermark + " " + "{}".format("unicast")
        elif 'queue_user_watermark_multicast' in argv:
            command = queue_user_watermark + " " + "{}".format("multicast")
        elif 'queue_user_watermark_cpu' in argv:
            command = queue_user_watermark + " " + "{}".format("CPU")
        elif 'queue_persistent_watermark_unicast' in argv:
            command = queue_persistent_watermark + " " + "{}".format("unicast")
        elif 'queue_persistent_watermark_multicast' in argv:
            command = queue_persistent_watermark + " " + "{}".format(
                "multicast")
        elif 'buffer_pool_watermark' in argv or 'percent' in kwargs:
            if cli_type == 'klish' and 'percent' in kwargs:
                perc = 'percentage'
            else:
                perc = kwargs.get('percent', '')
            command = "show buffer_pool watermark {}".format(perc)
        elif 'buffer_pool_persistent-watermark' in argv or 'percent' in kwargs:
            if cli_type == 'klish' and 'percent' in kwargs:
                perc = 'percentage'
            else:
                perc = kwargs.get('percent', '')
            command = "show buffer_pool persistent-watermark {}".format(perc)
        elif 'column_name' and 'queue_value' in kwargs:
            intf_name = st.get_other_names(
                dut, [kwargs['interface_name']])[0] if '/' in kwargs[
                    'interface_name'] else kwargs['interface_name']
            command = redis.build(
                dut, redis.COUNTERS_DB,
                "hget {} {}:{}".format(kwargs['column_name'], intf_name,
                                       kwargs['queue_value']))
            output = st.show(dut, command)
            oid = output[0]['oid'].strip('"')
            command = redis.build(
                dut, redis.COUNTERS_DB,
                "hgetall {}:{}".format(kwargs['table_name'], oid))
            output = st.show(dut, command)
            output = output[:-1]
            dut_output = get_dict_from_redis_cli(output)
            st.log(dut_output)
            return [dut_output]
        elif 'buffer_pool_counters_DB' in argv:
            command = redis.build(dut, redis.COUNTERS_DB,
                                  "Hgetall COUNTERS_BUFFER_POOL_NAME_MAP")
            output = st.show(dut, command)
            output = output[:-1]
            dut_output = get_dict_from_redis_cli(output)
            st.log(dut_output)
            command = redis.build(
                dut, redis.COUNTERS_DB, "hgetall COUNTERS:{}".format(
                    dut_output[kwargs['oid_type']].strip('"')))
            output = st.show(dut, command)
            output = output[:-1]
            dut_output = get_dict_from_redis_cli(output)
            st.log(dut_output)
            return [dut_output]
        if 'port_alias' in kwargs or 'percentage' in kwargs:
            if cli_type == 'click':
                command += " {} | grep -w {}".format(
                    kwargs.get('percentage', ''), kwargs['port_alias'])
                return st.show(dut, command, type=cli_type)
            elif cli_type == 'klish':
                if kwargs['port_alias'] == 'CPU':
                    command += " | grep {}".format(kwargs['port_alias'])
                else:
                    interface_details = get_interface_number_from_name(
                        kwargs['port_alias'])
                    if 'percentage' in kwargs:
                        using_perc = command.split(" ")
                        using_perc.insert(-1, "percentage")
                        command = " ".join(using_perc)
                        command += " interface {} {}".format(
                            interface_details.get("type"),
                            interface_details.get("number"))
                    else:
                        command += " interface {} {}".format(
                            interface_details.get("type"),
                            interface_details.get("number"))
        return st.show(dut, command, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        ret_val = list()
        rest_urls = st.get_datastore(dut, "rest_urls")
        if "snapshot_interval" in argv:
            url = rest_urls['get_watermark_interval']
            get_info = get_rest(dut, rest_url=url, timeout=60)
            temp = dict()
            temp['snapshotinterval'] = get_info['output'][
                'openconfig-qos-ext:watermark']['state']['refresh-interval']
            ret_val.append(temp)
            st.debug(ret_val)
            return ret_val
        elif 'telemetry_interval' in argv:
            url = rest_urls['get_telemetry_interval']
            get_info = get_rest(dut, rest_url=url, timeout=60)
            temp = dict()
            temp['telemetryinterval'] = get_info['output'][
                'openconfig-qos-ext:telemetry-watermark']['state'][
                    'refresh-interval']
            ret_val.append(temp)
            st.debug(ret_val)
            return ret_val
        for queue_type in argv:
            if 'port_alias' in kwargs or 'percentage' in kwargs:
                ret_val = list()
                rest_urls = st.get_datastore(dut, "rest_urls")
                if queue_type in [
                        'queue_user_watermark_unicast',
                        'queue_user_watermark_multicast',
                        'queue_persistent_watermark_unicast',
                        'queue_persistent_watermark_multicast',
                        'queue_user_watermark_cpu'
                ]:
                    url = rest_urls['get_queue_counter_values'].format(
                        kwargs['port_alias'])
                    get_info = get_rest(dut, rest_url=url, timeout=60)
                    for entry in get_info['output']['openconfig-qos:queues'][
                            'queue']:
                        temp = dict()
                        counters_info = entry['state']
                        port, queue = counters_info['name'].split(':')
                        type = counters_info["openconfig-qos-ext:traffic-type"]
                        counter = type.lower() + queue
                        if kwargs['port_alias'] == 'CPU':
                            cpu_counter = port + queue
                            temp['queue'] = cpu_counter
                            temp['bytes'] = counters_info[
                                "openconfig-qos-ext:watermark"]
                        if 'percentage' in kwargs:
                            if queue_type in [
                                    'queue_user_watermark_unicast',
                                    'queue_user_watermark_multicast'
                            ]:
                                temp[counter] = counters_info[
                                    "openconfig-qos-ext:watermark-percent"]
                            elif queue_type in [
                                    'queue_persistent_watermark_unicast',
                                    'queue_persistent_watermark_multicast'
                            ]:
                                temp[counter] = counters_info[
                                    "openconfig-qos-ext:persistent-watermark-percent"]
                        else:
                            if queue_type in [
                                    'queue_user_watermark_unicast',
                                    'queue_user_watermark_multicast'
                            ]:
                                temp[counter] = counters_info[
                                    "openconfig-qos-ext:watermark"]
                            elif queue_type in [
                                    'queue_persistent_watermark_unicast',
                                    'queue_persistent_watermark_multicast'
                            ]:
                                temp[counter] = counters_info[
                                    "openconfig-qos-ext:persistent-watermark"]
                        ret_val.append(temp)
                    st.debug(ret_val)
                    return ret_val
                if queue_type in [
                        'persistent_PG_shared', 'user_watermark_PG_shared',
                        'persistent_PG_headroom', 'user_watermark_PG_headroom'
                ]:
                    url = rest_urls['get_pg_counter_values'].format(
                        kwargs['port_alias'])
                    get_info = get_rest(dut, rest_url=url, timeout=60)
                    for entry in get_info['output'][
                            'openconfig-qos-ext:priority-groups'][
                                'priority-group']:
                        temp = dict()
                        counters_info = entry['state']
                        port, queue = counters_info['name'].split(':')
                        for i in range(0, 8):
                            if queue == str(i):
                                counter = 'pg' + str(i)
                                if 'percentage' in kwargs:
                                    if queue_type == 'user_watermark_PG_shared':
                                        temp[counter] = counters_info[
                                            'shared-watermark-percent']
                                    elif queue_type == 'user_watermark_PG_headroom':
                                        temp[counter] = counters_info[
                                            'headroom-watermark-percent']
                                    elif queue_type == 'persistent_PG_shared':
                                        temp[counter] = counters_info[
                                            'shared-persistent-watermark-percent']
                                    elif queue_type == 'persistent_PG_headroom':
                                        temp[counter] = counters_info[
                                            'headroom-persistent-watermark-percent']
                                else:
                                    if queue_type == 'user_watermark_PG_shared':
                                        temp[counter] = counters_info[
                                            'shared-watermark']
                                    elif queue_type == 'user_watermark_PG_headroom':
                                        temp[counter] = counters_info[
                                            'headroom-watermark']
                                    elif queue_type == 'persistent_PG_shared':
                                        temp[counter] = counters_info[
                                            'shared-persistent-watermark']
                                    elif queue_type == 'persistent_PG_headroom':
                                        temp[counter] = counters_info[
                                            'headroom-persistent-watermark']
                                ret_val.append(temp)
                    st.debug(ret_val)
                    return ret_val
    else:
        st.error("Unsupported UI Type: {} provided".format(cli_type))
        return False
Example #19
0
def config_static_ndp(dut,
                      ip6_address,
                      mac_address,
                      interface,
                      operation="add",
                      **kwargs):
    """
    Config static ndp
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :param ip6_address:
    :param mac_address:
    :param interface:
    :param operation:
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    command = ''
    if cli_type == 'click':
        interface = st.get_other_names(
            dut, [interface])[0] if '/' in interface else interface
        oper = "replace" if operation == "add" else "del"
        command = "ip -6 neighbor {} {} lladdr {} dev {}".format(
            oper, ip6_address, mac_address, interface)
    elif cli_type == 'klish':
        command = list()
        intf = get_interface_number_from_name(interface)
        command.append('interface {} {}'.format(intf["type"], intf["number"]))
        cmd = 'ipv6 neighbor {} {}'.format(
            ip6_address, mac_address
        ) if operation == 'add' else 'no ipv6 neighbor {} {}'.format(
            ip6_address, mac_address)
        command.extend([cmd, 'exit'])
    elif cli_type in ['rest-patch', 'rest-put']:
        rest_urls = st.get_datastore(dut, 'rest_urls')
        port_index = get_subinterface_index(dut, interface)
        if operation == 'add':
            url = rest_urls['config_static_ndp'].format(name=interface,
                                                        index=port_index)
            config_data = {
                "openconfig-if-ip:neighbor": [{
                    "ip": ip6_address,
                    "config": {
                        "ip": ip6_address,
                        "link-layer-address": mac_address
                    }
                }]
            }
            if not config_rest(
                    dut, rest_url=url, http_method=cli_type,
                    json_data=config_data):
                st.error(
                    "Failed to configure static neighbor with IP: {} MAC: {} on INTF: {}"
                    .format(ip6_address, mac_address, interface))
                return False
        else:
            url = rest_urls['delete_static_ndp'].format(name=interface,
                                                        index=port_index,
                                                        ip=ip6_address)
            if not delete_rest(dut, rest_url=url):
                st.error(
                    "Failed to delete static neighbor with IP: {} MAC: {} on INTF: {}"
                    .format(ip6_address, mac_address, 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
Example #20
0
def gnmi_call(dut, **kwargs):
    """
    Call to test gnmi session using diff users w.r.t RBAC.
    Author : Prudvi Mangadu ([email protected])
    :param dut:
    :param kwargs:
    :return:
    """
    st.log('Performing gnmi operations using - {}'.format(kwargs))

    for each in ['login_type', 'username', 'password', 'mode']:
        if not kwargs.get(each):
            st.error("Mandatory argument is not found - {}".format(each))
            return False

    dut_ip = "127.0.0.1"
    result = {'gnmi_get_out': True, 'gnmi_set_out': True}
    result2 = True
    username = kwargs.get('username')
    password = kwargs.get('password')
    cert = kwargs.get('cert')
    login_type = kwargs.get('login_type')
    mode = kwargs.get('mode')
    port = st.get_free_ports(dut)[0]
    if "/" in port:
        port = st.get_other_names(dut, [port])[0]
    xpath = '/openconfig-interfaces:interfaces/interface[name={}]/config/description'.format(port)
    json_content = {"openconfig-interfaces:description": "Eth"}

    if login_type == 'cred':
        gnmi_set_out = gnmi_set(dut, xpath, json_content=json_content, ip_address=dut_ip, username=username,
                                password=password)
        st.log(gnmi_set_out)
        gnmi_get_out = gnmi_get(dut, xpath, ip_address=dut_ip, username=username, password=password)
        st.log(gnmi_get_out)

    elif login_type == 'cert':
        gnmi_set_out = gnmi_set(dut, xpath, json_content=json_content, ip_address=dut_ip, cert=cert,
                                username=None, password=None, insecure='none', target_name='admin')
        st.log(gnmi_set_out)
        gnmi_get_out = gnmi_get(dut, xpath, ip_address=dut_ip, cert=cert, username=None, password=None, insecure='none',
                                target_name='admin')
        st.log(gnmi_get_out)

    else:
        st.error("Invalid 'login_type' used = {}".format(login_type))
        return False

    if mode == 'rw':
        if not (gnmi_set_out and gnmi_get_out):
            st.report_fail('rbac_call_fail', "gNMI", mode, login_type)
    else:
        if not (not gnmi_set_out and gnmi_get_out):
            st.report_fail('rbac_call_fail', "gNMI", mode, login_type)

    msg = 'Failed to execute set command using gNMI session with mode- {mode}, type- {login_type}'
    if mode == 'rw' and "op: UPDATE" not in gnmi_set_out and "description" not in str(gnmi_get_out):
        st.error(msg.format(**kwargs))
        result2 = False
    if mode == 'ro' and not gnmi_set_out and "description" not in str(gnmi_get_out):
        st.error(msg.format(**kwargs))
        result2 = False

    if not result2:
        st.report_fail('rbac_test_status', 'Fail', mode, 'gNMI', login_type, result)
    st.report_pass('rbac_test_status', 'Pass', mode, 'gNMI', login_type, result)
Example #21
0
def tf_config_common_call(call_type, th_value, **kwargs):
    """
    Common function to make both CLI and REST threshold feature calls
    """
    result2 = 1
    dut = kwargs['dut']
    if call_type != "REST_CLEAR":
        threshold_type = kwargs['threshold_type']
        buffer_type = kwargs['buffer_type']
        index_name = kwargs['index_name']
        port_alias = kwargs['port_alias']
        index = int(re.findall(r"\d+", kwargs['index_name'])[0])

    if call_type == "REST_GET" or call_type == 'REST_GET_PORTS_CHECK':
        st.banner("Verifying Threshold {} {} config via REST".format(
            threshold_type, buffer_type))
        if any("/" in interface for interface in make_list(port_alias)):
            port_alias = st.get_other_names(vars.D1, make_list(port_alias))[0]
        get_rest_data = tfapi.get_threshold_rest_data(
            threshold_type=threshold_type,
            buffer_type=buffer_type,
            port=port_alias)
        rv_data = rtapi.send_rest_request(dut, tf_rest_data.feature,
                                          tf_rest_data.get_bst_thresholds,
                                          get_rest_data)
        if not rv_data:
            st.error("Failed to GET Threshold {} {} via REST".format(
                threshold_type, buffer_type))
            return 0
        if rv_data:
            resp = json.loads(rv_data.text)
            if call_type == 'REST_GET_PORTS_CHECK':
                st.banner("Validating interfaces in {} {} REST Data ".format(
                    threshold_type, buffer_type))
                if not check_ports_from_rest_output(resp, threshold_type,
                                                    buffer_type,
                                                    tf_rest_data.all_ports):
                    result2 = 0
                if result2:
                    st.log(
                        "--> Success: Interface Validation of {} {}  REST DATA"
                        .format(threshold_type, buffer_type))
            get_value = get_threshold_from_rest_output(resp, threshold_type,
                                                       buffer_type, port_alias,
                                                       index)
            if get_value is None:
                return 0
            st.log(
                "REST GET Threshold Value {} {} on Port:{}, Index:{}".format(
                    get_value, type(get_value), port_alias, index))
            st.log("Configured Threshold Value {} {}".format(
                th_value, type(th_value)))
            if not get_value == int(th_value):
                st.error("Failed to Verify Threshold {} {} via REST".format(
                    threshold_type, buffer_type))
                return 0
        st.log("--> Success: Verifying Threshold {} {} config via REST".format(
            threshold_type, buffer_type))
        return 1 and result2

    elif call_type == "REST_SET":
        st.banner("Configuring Threshold {} {} via REST".format(
            threshold_type, buffer_type))
        if any("/" in interface for interface in make_list(port_alias)):
            port_alias = st.get_other_names(vars.D1, make_list(port_alias))[0]
        set_rest_data = tfapi.set_threshold_rest_data(
            threshold_type=threshold_type,
            port_alias=port_alias,
            index=index,
            buffer_type=buffer_type,
            value=th_value)
        if not rtapi.send_rest_request(dut, tf_rest_data.feature,
                                       tf_rest_data.configure_bst_thresholds,
                                       set_rest_data):
            st.error("Failed to SET Threshold {} {} via REST".format(
                threshold_type, buffer_type))
            return 0
        st.log("--> Success: Configuring Threshold {} {} via REST".format(
            threshold_type, buffer_type))
        return 1

    elif call_type == 'CLI_GET':
        st.banner("Verifying Threshold {} {} config via CLI".format(
            threshold_type, buffer_type))
        api_data = {
            'threshold_type': threshold_type,
            'buffer_type': buffer_type,
            'port_alias': port_alias,
            index_name: th_value
        }
        if not tfapi.verify_threshold(dut, **api_data):
            st.error("Failed to Verify Threshold {} {} via CLI".format(
                threshold_type, buffer_type))
            return 0
        st.log("--> Success: Verifying Threshold {} {} config via CLI".format(
            threshold_type, buffer_type))
        return 1

    elif call_type == 'REST_CLEAR':
        st.banner("Performing Clear BST thresholds via REST")
        if not rtapi.send_rest_request(dut, tf_rest_data.feature,
                                       tf_rest_data.clear_bst_thresholds, {}):
            st.error('REST: Clear BST thresholds call failed')
            return 0
        st.log("--> Success: Performing Clear thresholds via REST")
        return 1
    else:
        st.error("Unknown tf call_type : {}".format(call_type))
        return 0