Example #1
0
 def apply(self, request, sections=None, operations=None, ui="rest"):
     if ui == "cli": return self.cli(request, sections, operations)
     retval = SpyTestDict()
     if operations: operations = utils.make_list(operations)
     for index, ent in enumerate(utils.make_list(request)):
         enable = ent.get("enable", 1)
         if not enable: continue
         operation = ent["operation"]
         if operations and operation not in operations: continue
         instance = ent.get("instance", dict())
         data = ent.get("data", dict())
         path = ent.get("path", "")
         name = ent.get("name", "{}".format(index))
         if operation == "read" or operation == "get":
             retval[name] = self.get(path, **instance)
         elif operation == "configure" or operation == "patch":
             retval[name] = self.patch(path, data, **instance)
         elif operation == "unconfigure" or operation == "delete":
             retval[name] = self.delete(path, **instance)
         elif operation == "post":
             retval[name] = self.post(path, data, **instance)
         elif operation == "put":
             retval[name] = self.put(path, data, **instance)
         elif operation == "verify":
             resp = self.get(path, **instance)
             result = [True, []]
             for pe in jsonpatch.make_patch(data, resp.output):
                 result[1].append(pe)
                 if pe["op"] != "add":
                     result[0] = False
             retval[name] = result
     return retval
Example #2
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 #3
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 #4
0
def verify(dut, *argv, **kwargs):
    """
    Generic verify API.
    Author : Prudvi Mangadu ([email protected])
    :param dut:
    :param argv:
    :param kwargs:
    :Usage:
        verify(vars.D1, 'logged_users', verify_list=[{'user':'******'}, {'user':'******'user_list', verify_list=['admin', 'test1'])
        verify(vars.D1, 'group_list', verify_list=['admin','operator'])
        verify(vars.D1, user_group='admin', verify_list=[{'group':'admin'}])
    """
    result = True
    if not kwargs.get('verify_list'):
        st.error("Mandatory parameter -verify_list is missing")
        return False
    out = show(dut, *argv, **kwargs)
    if 'logged_users' in argv or kwargs.get('user_group'):
        for each in make_list(kwargs.get('verify_list')):
            if not filter_and_select(out, None, each):
                st.log("{} - {} is not match".format(each, out))
                result = False

    if 'user_list' in argv or 'group_list' in argv:
        for each in make_list(kwargs.get('verify_list')):
            if each not in out:
                st.log("{} - is not found in {}".format(each, out))
                result = False

    return result
Example #5
0
 def cli(self, request, sections=None, operations=None):
     retval = SpyTestDict()
     map_operations={"create":"post", "read":"get", "update":"put", "modify":"patch", "delete":"delete"}
     if operations: operations = utils.make_list(operations)
     for index, ent in enumerate(utils.make_list(request)):
         key = ent.path.replace("/restconf/data", map_operations[ent.operation])
         key = key.replace("-", "_").replace(":", "_").replace("/", "_")
         cli = self.search_cli(key)
         if not cli:
             print("Rest2CLI Fail: {} {}".format(key, ent.path))
             self.search_cli_data(request.data)
             continue
         print("Rest2CLI PASS: {} {}".format(key, cli.cmd))
     return retval
Example #6
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 #7
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 #8
0
def verify(dut, **kwargs):
    """
    Call to verify - show ip igmp snooping
    Author : Prudvi Mangadu ([email protected])
    :param :dut:
    :param :cli_type:   default - klish
    :param :vlan
    :param :mrouter_interface
    :param :querier
    :param :igmp_operation_mode
    :param :fast_leave
    :param :query_max_response_time
    :param :last_member_query_interval
    :param :query_interval
    :return:
    """
    result = True
    output = show(dut, **kwargs)
    match = {
        e: kwargs[e]
        for e in kwargs if e not in ['cli_type', 'mrouter_interface']
    }
    entries = utils.filter_and_select(output, None, match)
    if not entries:
        st.log("match {} is not in output {}".format(match, entries))
        result = False
    if "mrouter_interface" in kwargs:
        interface_li = utils.make_list(kwargs['mrouter_interface'])
        for each in interface_li:
            if each not in entries[0]['mrouter_interface'].split(', '):
                st.log(
                    "Mrouter interface {} is not found under mentioned vlan".
                    format(each))
                result = False
    return result
Example #9
0
def get_interface_pmap_details(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:
    """
    ##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 = utils.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 = bcmcmd_show_pmap(dut)
    for detail in utils.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
def verify(dut, **kwargs):
    cli_type = st.get_ui_type(dut, **kwargs)
    """
    Author : Kiran Vedula ([email protected])
    :param :dut:
    :param :vrf_name:
    :param :interfaces:
    verify(vars.D1, vrf_name='management', interfaces=['eth0'])
    """
    interface_li = utils.make_list(kwargs.get('interfaces'))
    output = show(dut, cli_type=cli_type)
    if cli_type == 'klish':
        if not output:
            st.error("Unable to get command output")
            return False
        else:
            if output[0]['interface'] != 'eth0':
                st.log("Mgmt VRF not bound to eth0")
                return False
    elif cli_type == 'click':
        if not output:
            st.error("Unable to get command output")
            return False
        if output['mvrfstate'] != kwargs.get('mvrfstate'):
            st.log("Management VRF state mismatch")
            return False
        if output['mvrfstate'] == "Enabled":
            match = list()
            for each in interface_li:
                match.append({'mvrf_interface': each})
            intf_list = utils.filter_and_select(output["interfaces"], None,
                                                match)
            if kwargs.get('dataport'):
                if intf_list:
                    st.log(
                        "No match available for - {} in output".format(match))
                    return False
            else:
                if not intf_list:
                    st.log(
                        "No match available for - {} in output".format(match))
                    return False
    elif cli_type in ["rest-patch", "rest-put"]:
        if not output:
            st.log("Unable to get Rest operation Get output")
            return False
        if not rest_status(output["status"]):
            st.log("rest_call_failed", "GET")
            return False
        if output["output"]["openconfig-network-instance:state"][
                "name"] != "mgmt":
            st.log("Mgmt VRF not bound to eth0")
            return False
        if not output["output"]["openconfig-network-instance:state"]["enabled"]:
            st.log("Management VRF state mismatch")
            return False
    else:
        st.error("Unsupported cli_type: {}".format(cli_type))
        return False
    return True
Example #11
0
def verify_interface_status(dut, interface, property, value, cli_type="click"):
    """
    Author: Chaitanya Vella ([email protected])
    This API to verify the interface status
    :param dut: dut obj
    :param interface: Interface Name
    :param property: Interface property
    :param value: Property Value
    :param cli_type:
    :return: Boolean
    """
    interface_list = make_list(interface)
    is_found = 1
    for port in interface_list:
        interface_details = interface_status_show(dut, port, cli_type=cli_type)
        match = {"interface": port, property: value}
        entries = filter_and_select(interface_details, ["interface"], match)
        if not bool(entries):
            is_found = 0
            break
        else:
            is_found = 1
    if not is_found:
        return False
    return True
Example #12
0
def verify_hardware_map_status(dut, queues, itter_count=30, delay=1):
    """
    To verify the Queue init in hardware
    :param dut:
    :param queues:
    :param itter_count:
    :param delay:
    :return:
    """
    command = redis.build(dut, redis.COUNTERS_DB, "keys *MAP*")
    queues_li = utils.make_list(queues)
    i = 1
    while True:
        output = st.show(dut, command)
        output_list = utils.filter_and_select(output, ["name"], None)
        output_list = utils.dicts_list_values(output_list, "name")
        result = True
        for each_q in queues_li:
            if each_q not in output_list:
                st.log("{} not yet init.".format(each_q))
                result = False
        if result:
            return True
        if i > itter_count:
            st.log("Max {} tries Exceeded.Exiting..".format(i))
            return False
        i += 1
        st.wait(delay)
Example #13
0
def show_interfaces_counters(dut,
                             interface=None,
                             property=None,
                             cli_type="click"):
    """
    show interface counter
    Author : Prudvi Mangadu ([email protected])
    :param dut:
    :param interface:
    :param property:
    :param cli_type:
    :return:
    """
    if cli_type == "click":
        command = 'show interfaces counters'
        output = st.show(dut, command)
        if interface:
            if property:
                output = filter_and_select(output, [property],
                                           {'iface': interface})
            else:
                output = filter_and_select(output, None, {'iface': interface})
        return output
    elif cli_type == "klish":
        command = "show interface counters"
        interface = make_list(interface)
        if interface:
            command += " | grep \"{}\"".format("|".join(interface))
        return st.show(dut, command, type=cli_type)
    else:
        st.log("Unsupported CLI TYPE {}".format(cli_type))
        return False
Example #14
0
def ensure_cli_type(cli_type, expected=list()):
    if cli_type not in make_list(expected):
        st.log("UNSUPPORTED CLI TYPE {} -- EXPECTING {}".format(
            cli_type, expected))
        return False
    else:
        return True
Example #15
0
def check_unwanted_logs_in_logging(dut, user_filter=None):
    """
    Check unwanted log based on uers filter list
    Author: Prudvi Mangadu ([email protected])
    :param dut:
    :param user_filter:
    :return:
    """
    result = True
    static_filter = ['i2c', 'fan', 'power']
    over_all_filter = static_filter + make_list(
        user_filter) if user_filter else static_filter
    for filter in over_all_filter:
        temp_count = get_logging_count(dut, filter_list=filter)
        st.debug("{} - logs found on the error string '{}'".format(
            temp_count, filter))
        if temp_count:
            if filter == 'fan':
                filters = ["INFO system#monitor: MEM :: Name:fand"]
                logs = show_logging(dut, filter_list=filter)
                for log in logs:
                    if not any(fil.lower() in log.lower() for fil in filters):
                        result = False
            else:
                result = False
    return result
Example #16
0
def list_filter_and_select(data, filter_list):
    """
      This will search all elements in data list w.r.t to filter list and return matched elements of data.
    Author : Prudvi Mangadu ([email protected])
    :param data: list
    :param filter_list: list
    :return:
    """
    result = []
    filter_li = make_list(filter_list)
    st.debug("Filter List : {}".format(filter_li))
    for each in make_list(data):
        if len([x for x in filter_li if re.search(x, each)]) == len(filter_li):
            st.debug("Match Found : {}".format(each))
            result.append(each)
    return result
Example #17
0
def _get_rest_dhcp_relay_statistics(dut, interface="", family='ipv4'):
    """
    To get the dhcp-relay statistics data
    Author Jagadish Chatrasi ([email protected])
    :param dut:
    :param interface:
    :param family:
    :return:
    """
    retval = list()
    rest_urls = st.get_datastore(dut, 'rest_urls')
    ip_string = '' if family == 'ipv4' else 'v6'
    if not interface:
        output = get_interface_ip_address(dut, family=family)
        interfaces = {entry['interface'] for entry in output}
        interfaces.discard('eth0')
    else:
        interfaces = make_list(interface)
    for intf in interfaces:
        url = rest_urls['get_dhcp{}_relay_counters'.format(ip_string)].format(id=intf)
        out = get_rest(dut, rest_url=url)
        if isinstance(out, dict) and out.get('output') and out['output'].get('openconfig-relay-agent:counters') and isinstance(out['output']['openconfig-relay-agent:counters'], dict):
            data = out['output']['openconfig-relay-agent:counters']
            temp = dict()
            if family == 'ipv4':
                temp['bootrequest_msgs_received_by_the_relay_agent'] = str(data['bootrequest-received']) if data.get('bootrequest-received') else '0'
                temp['bootrequest_msgs_forwarded_by_the_relay_agent'] = str(data['bootrequest-sent']) if data.get('bootrequest-sent') else '0'
                temp['bootreply_msgs_forwarded_by_the_relay_agent'] = str(data['bootreply-sent']) if data.get('bootreply-sent') else '0'
                temp['dhcp_ack_msgs_sent_by_the_relay_agent'] = str(data['dhcp-ack-sent']) if data.get('dhcp-ack-sent') else '0'
                temp['dhcp_decline_msgs_received_by_the_relay_agent'] = str(data['dhcp-decline-received']) if data.get('dhcp-decline-received') else '0'
                temp['dhcp_discover_msgs_received_by_the_relay_agent'] = str(data['dhcp-discover-received']) if data.get('dhcp-discover-received') else '0'
                temp['dhcp_inform_msgs_received_by_the_relay_agent'] = str(data['dhcp-inform-received']) if data.get('dhcp-inform-received') else '0'
                temp['dhcp_nack_msgs_sent_by_the_relay_agent'] = str(data['dhcp-nack-sent']) if data.get('dhcp-nack-sent') else '0'
                temp['dhcp_offer_msgs_sent_by_the_relay_agent'] = str(data['dhcp-offer-sent']) if data.get('dhcp-offer-sent') else '0'
                temp['dhcp_release_msgs_received_by_the_relay_agent'] = str(data['dhcp-release-received']) if data.get('dhcp-release-received') else '0'
                temp['dhcp_request_msgs_received_by_the_relay_agent'] = str(data['dhcp-request-received']) if data.get('dhcp-request-received') else '0'
                temp['number_of_dhcp_pkts_drpd_due_to_an_invd_opcode'] = str(data['invalid-opcode']) if data.get('invalid-opcode') else '0'
                temp['number_of_dhcp_pkts_drpd_due_to_an_invd_option'] = str(data['invalid-options']) if data.get('invalid-options') else '0'
                temp['total_nbr_of_dhcp_pkts_drpd_by_the_relay_agent'] = str(data['total-dropped']) if data.get('total-dropped') else '0'
            else:
                temp['dhcpv6_advt_msgs_sent_by_the_relay_agent'] = str(data['dhcpv6-adverstise-sent']) if data.get('dhcpv6-adverstise-sent') else '0'
                temp['dhcpv6_confirm_msgs_rcvd_by_the_relay_agent'] = str(data['dhcpv6-confirm-received']) if data.get('dhcpv6-confirm-received') else '0'
                temp['dhcpv6_decline_msgs_rcvd_by_the_relay_agent'] = str(data['dhcpv6-decline-received']) if data.get('dhcpv6-decline-received') else '0'
                temp['dhcpv6_info_rqst_msgs_rcvd_by_the_relay_agent'] = str(data['dhcpv6-info-request-received']) if data.get('dhcpv6-info-request-received') else '0'
                temp['dhcpv6_rebind_msgs_rcvd_by_the_relay_agent'] = str(data['dhcpv6-rebind-received']) if data.get('dhcpv6-rebind-received') else '0'
                temp['dhcpv6_reconfig_msgs_sent_by_the_relay_agent'] = str(data['dhcpv6-reconfigure-sent']) if data.get('dhcpv6-reconfigure-sent') else '0'
                temp['dhcpv6_relay_fwd_msgs_sent_by_the_relay_agent'] = str(data['dhcpv6-relay-forw-sent']) if data.get('dhcpv6-relay-forw-sent') else '0'
                temp['dhcpv6_relay_reply_msgs_rcvd_by_the_relay_agent'] = str(data['dhcpv6-relay-reply-received']) if data.get('dhcpv6-relay-reply-received') else '0'
                temp['dhcpv6_release_msgs_rcvd_by_the_relay_agent'] = str(data['dhcpv6-release-received']) if data.get('dhcpv6-release-received') else '0'
                temp['dhcpv6_reply_msgs_sent_by_the_relay_agent'] = str(data['dhcpv6-reply-sent']) if data.get('dhcpv6-reply-sent') else '0'
                temp['dhcpv6_rqst_msgs_rcvd_by_the_relay_agent'] = str(data['dhcpv6-request-received']) if data.get('dhcpv6-request-received') else '0'
                temp['dhcpv6_solic_msgs_rcvd_by_the_relay_agent'] = str(data['dhcpv6-solicit-received']) if data.get('dhcpv6-solicit-received') else '0'
                temp['number_of_dhcpv6_pkts_drpd_due_to_an_inv_opcode'] = str(data['invalid-opcode']) if data.get('invalid-opcode') else '0'
                temp['number_of_dhcpv6_pkts_drpd_due_to_an_inv_option'] = str(data['invalid-options']) if data.get('invalid-options') else '0'
                temp['total_nbr_of_dhcpv6_pkts_drpd_by_the_relay_agent'] = str(data['total-dropped']) if data.get('total-dropped') else '0'
            retval.append(temp)
    st.debug(retval)
    return retval
Example #18
0
def get_crm_thresholds(dut, family, cli_type=""):
    """
    GET CRM Threshold w.r.t family.
    Author : Prudvi Mangadu ([email protected])
    :param dut:
    :param family:
    :param cli_type: click or klish designation:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    family = family.lower()
    # Handling few show crm family cli commands
    if family in ['acl_group_entry', 'acl_group_counter', 'acl_table_stats']:
        if st.is_feature_supported("crm-all-families", dut):
            family = 'all'
            cli_type = 'klish'
    family_list = crm_get_family_list(dut)
    if family not in family_list:
        log = "family:'{}' is invalid , use any of valid family from - {}".format(
            family, ','.join(family_list))
        st.error(log)
        return False
    if cli_type == "click":
        command = 'crm show thresholds {}'.format(family.replace('_', ' '))
        output = st.show(dut, command, type=cli_type)
    elif cli_type == "klish":
        command = 'show crm thresholds {}'.format(family.replace('_', ' '))
        output = st.show(dut, command, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        output = list()
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['crm_thresholds']
        result = get_rest(
            dut, rest_url=url)["output"]["openconfig-system-crm:threshold"]
        family_mapping = {
            "nexthop_group_member": "nexthop_group-member",
            "nexthop_group_object": "nexthop_group-object"
        }
        families = make_list(family)
        if "all" in families:
            families = family_list
            families.remove("all")
        for family2 in families:
            crm_threshold = {}
            crm_threshold["resourcename"] = family2
            family2 = family_mapping.get(family2, family2).split("_")
            for each in family2:
                result = result[each]
            if result["state"].get("type", ""):
                crm_threshold["thresholdtype"] = result["state"]["type"].lower(
                )
                crm_threshold["highthreshold"] = result["state"]["high"]
                crm_threshold["lowthreshold"] = result["state"]["low"]
                output.append(crm_threshold)
    else:
        st.error("Unsupported cli type: {}".format(cli_type))
        return False
    return output
Example #19
0
def debug_bgp_bfd(dut):
    dut_list = make_list(dut)
    st.banner("********* Dubug commands starts ************")
    func_list = [clear_interface_counters, show_arp, show_ndp, show_interface_counters_all,
                 asicapi.dump_l3_ip6route, asicapi.dump_l3_defip]
    for func in func_list:
        api_list = [[func, dut] for dut in dut_list]
        exec_all(True, api_list)
    st.banner(" ******** End of Dubug commands ************")
Example #20
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 #21
0
def verify(dut, *argv, **kwargs):
    """
    Generic verify API.
    Author : Prudvi Mangadu ([email protected])
    :param dut:
    :param argv:
    :param kwargs:
    :Usage:
        verify(vars.D1, 'logged_users', verify_list=[{'user':'******'}, {'user':'******'user_list', verify_list=['admin', 'test1'])
        verify(vars.D1, 'group_list', verify_list=['admin','operator'])
        verify(vars.D1, user_group='admin', verify_list=[{'group':'admin'}])
    """
    cli_type = kwargs.get("cli_type", "")
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    result = True
    if not kwargs.get('verify_list'):
        st.error("Mandatory parameter -verify_list is missing")
        return False
    out = show(dut, *argv, **kwargs)
    if 'logged_users' in argv or kwargs.get('user_group'):
        for each in make_list(kwargs.get('verify_list')):
            if cli_type == "click":
                if not filter_and_select(out, None, each):
                    st.log("{} - {} is not match".format(each, out))
                    result = False
            else:
                out[0]['secondary_group'] = re.findall(
                    r'\(([^)]+)', out[0]['secondary_group'])
                if each['group'] == 'sudo':
                    each['group'] = 'operator'
                if each['group'] not in out[0]['secondary_group']:
                    st.log("{} - {} is not match".format(each, out))
                    result = False
    if 'user_list' in argv or 'group_list' in argv:
        for each in make_list(kwargs.get('verify_list')):
            if each not in out:
                st.log("{} - is not found in {}".format(each, out))
                result = False

    return result
Example #22
0
def config_server(dut, no_form=False, skip_error_check=False, **kwargs):
    """
    Config / Unconfig radius server using provided parameters
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :param family:
    :param no_form:
    :param kwargs:
    :return:
    """
    st.log("Configuring RADIUS SERVER Parameters ...")
    cli_type = kwargs["cli_type"] if kwargs.get("cli_type") else "klish"
    if "ip_address" not in kwargs:
        st.log("IP Address not provided")
        return False
    ipaddress_li = common_utils.make_list(kwargs["ip_address"])
    for each_ip in ipaddress_li:
        if cli_type == "klish":
            cmd = "radius-server host {}".format(each_ip)
            if "auth_type" in kwargs:
                cmd += " auth-type {}".format(kwargs["auth_type"])
            if "auth_port" in kwargs:
                cmd += " auth-port {}".format(kwargs["auth_port"])
            if "key" in kwargs:
                cmd += " key {}".format(kwargs["key"])
            if "priority" in kwargs:
                cmd += " priority {}".format(kwargs["priority"])
            if "timeout" in kwargs:
                cmd += " timeout {}".format(kwargs["timeout"])
            if "use_mgmt_vrf" in kwargs:
                cmd += " vrf {}".format(kwargs.get("use_mgmt_vrf"))
            if "retransmit" in kwargs:
                cmd += " re-transmit {}".format(kwargs["retransmit"])
            command = "no {}".format(cmd) if no_form else cmd
            st.cli_config(dut, command, "mgmt-config", skip_error_check)
        elif cli_type == "click":
            action = kwargs["action"] if "action" in kwargs else "add"
            command = "config radius {} {}".format(action, each_ip)
            if "retransmit" in kwargs:
                command += " -r {}".format(kwargs["retransmit"])
            if "auth_type" in kwargs:
                command += " -a {}".format(kwargs["auth_type"])
            if "timeout" in kwargs:
                command += " -t {}".format(kwargs["timeout"])
            if "key" in kwargs:
                command += " -k {}".format(kwargs["key"])
            if "auth_port" in kwargs:
                command += " -o {}".format(kwargs["auth_port"])
            if "priority" in kwargs:
                command += " -p {}".format(kwargs["priority"])
            if "use_mgmt_vrf" in kwargs:
                command += " -m"
            st.config(dut, command, skip_error_check=skip_error_check)
Example #23
0
def show_stp_in_parallel(dut_list, thread=True, cli_type='click'):
    """
    API to show the stp configuration in parallel in all the provided DUT's
    Author: Chaitanya Vella ([email protected])
    :param dut_list:
    :param thread:
    :param cli_type:
    :return:
    """
    st.log("Displaying STP result on all the DUT's in parallel ....")
    dut_li = utility.make_list(dut_list)
    exec_foreach(thread, dut_li, show_stp, cli_type=cli_type)
Example #24
0
def interface_status_show(dut, interfaces=None, cli_type="click"):
    """
       Author: Chaitanya Vella ([email protected])
    Function to get the interface(s) status
    :param dut:
    :param interfaces:
    :param cli_type:
    :return:
    """
    if cli_type == "click":
        if interfaces:
            return portapi.get_status(dut, ','.join(make_list(interfaces)))
        return portapi.get_status(dut, interfaces)
    elif cli_type == "klish":
        command = "show interface status"
        interface = make_list(interfaces)
        if interface:
            command += " | grep \"{}\"".format("|".join(interface))
        return st.show(dut, command, type=cli_type)
    else:
        st.log("Unsupported CLI TYPE {}".format(cli_type))
        return False
Example #25
0
def reset_port_shaper_params(dut, policy_name, params_list, **kwargs):
    """
    API to reset Port-Level shaper parameters
    :param dut:
    :type dut:
    :param policy_name:
    :type policy_name:
    :param params_list:
    :type params_list:
    :return:
    :rtype:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    cli_type = 'klish' if cli_type == 'click' else cli_type
    skip_error = kwargs.get('skip_error', False)
    params_list = [param.lower() for param in make_list(params_list)]
    if cli_type == 'klish':
        commands = list()
        commands.append("qos scheduler-policy {}".format(policy_name))
        commands.append("port")
        commands.extend(["no {}".format(param) for param in params_list])
        commands.extend(["exit", "exit"])
        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')
        for param in params_list:
            if param.lower() not in ['pir', 'pbs']:
                st.error('Invalid port shaper parameter: {}'.format(param))
                return False
            if param == 'pir':
                url = rest_urls['shaper_pir_config'].format(policy_name, 255)
                if not delete_rest(dut, rest_url=url):
                    st.error("Failed to reset {} for port shaper profile: {}".
                             format(param, policy_name))
                    return False
            if param == 'pbs':
                url = rest_urls['shaper_pbs_config'].format(policy_name, 255)
                if not delete_rest(dut, rest_url=url):
                    st.error("Failed to reset {} for port shaper profile: {}".
                             format(param, policy_name))
                    return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True
Example #26
0
def default_user_password_finder(dut, username, password_list):
    """
    To Find default user password.
    Author : Prudvi Mangadu ([email protected])
    :param dut:
    :param username:
    :param password_list:
    :return:
    """
    st.log(" # Finding default user password.")
    for each_pass in make_list(password_list):
        st.log('Trying SSH connection to device with username={},password={}'.format(username, each_pass))
        if st.exec_ssh(dut, username, each_pass, ['show system status']):
            st.log("Detected password = {}".format(each_pass))
            return each_pass
Example #27
0
def config_igmp_snooping(dut, vlan, version, mode, clitype=""):
    """
    :param dut: D1
    :param vlan: List of vlans
    :param version: 1,2 or 3
    :param mode: enable or disable
    :param clitype:
    """
    if not clitype: clitype = st.get_ui_type(dut)
    vlan_list = utils.make_list(vlan)
    if mode == "enable":
        for i in vlan_list:
            config(dut, "mode", vlan=i, version=version, cli_type=clitype)
    else:
        for i in vlan_list:
            config(dut, "no_form", "mode", vlan=i, cli_type=clitype)
Example #28
0
def verify_dhcp_relay(dut, interface, dhcp_relay_addr, family="ipv4", cli_type=""):
    """
    API to verify DHCP RELAY configuration
    Author Chaitanya Vella ([email protected])
    :param dut:
    :param interface:
    :param dhcp_relay_addr:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    output = dhcp_relay_show(dut, family=family, interface=interface, cli_type=cli_type)
    dhcp_relay_address = make_list(dhcp_relay_addr)
    filter=list()
    for address in dhcp_relay_address:
        match = {"intf": interface, "dhcprelay_addr": address}
        filter.append(match)
    entries = filter_and_select(output, ["intf"], filter)
    return True if entries else False
Example #29
0
def psample_stats(dut, attr_data):
    """
    API to get psampe stats
    :param dut:
    :param attr_list: ["drop_sampling", "psample", "psample_cb"]
    :return:
    """
    result = dict()
    attr_list = common_utils.make_list(attr_data)
    output = st.show(dut, "sudo cat /proc/bcm/knet-cb/psample/stats")
    if not output:
        st.log("Output not found")
        return result
    for attr in attr_list:
        if attr in output[0]:
            result[attr] = output[0][attr]
    return result
Example #30
0
def verify(dut, *argv, **kwargs):
    """
    To perform Verify operations of IP Helper show cmds.
     Author: Prudvi Mangadu ([email protected])
    :param :dut:
    :param :verify_list:
    Usage:
        verify(vars.D1, forward_protocol='',
                                verify_list=[{'forwarding':'Enable', 'enable_ports':['23'] ,'disable_ports':['333']}])
        verify(vars.D1, helper_address='', verify_list=[{'interface':'Ethernet0', 'vrf:''black',
                                                                'relay_address':'1.2.3.4'}])
        verify(vars.D1, helper_address="Ethernet0",
                            verify_list=[{'interface':'Ethernet0', 'vrf':'black', 'relay_address':'1.2.3.4'}])
        verify(vars.D1, statistics="Ethernet0", verify_list=[{'packets_received':'0'}])
    """
    result = True
    if not kwargs.get('verify_list'):
        st.error("verify_list values are not provided")
        return False
    output = show(dut, *argv, **kwargs)
    for each in make_list(kwargs['verify_list']):
        if each.get('enable_ports'):
            for port in output[0]['enable_ports'].split(","):
                if port.strip() not in each.get('enable_ports'):
                    st.log("Port {} not in enable_ports {}".format(
                        port.strip(), output))
                    result = False
            each.pop('enable_ports')

        if each.get('disable_ports'):
            for port in output[0]['disable_ports'].split(","):
                if port.strip() not in each.get('disable_ports'):
                    st.log("Port {} not in disable_ports {}".format(
                        port.strip(), output))
                    result = False
            each.pop('disable_ports')

        if not filter_and_select(output, None, each):
            st.log("{} is not matching in the output {} ".format(each, output))
            result = False

    return result