Exemple #1
0
def verify_warm_restart(dut, **kwargs):
    """
    To verify warm restart state and config
    Author : Prudvi Mangadu ([email protected])

    :param dut:
    :param mode: config | state
    :param name:
    :param restore_count:
    :param state:
    :param enable:
    :param timer_name:
    :param timer_duration:
    :return:
    """

    if 'mode' not in kwargs:
        st.error("mode is not passed as argument to API.")
        return False
    if kwargs['mode'] in ['config', 'state']:
        command = "show warm_restart {}".format(kwargs['mode'])
    else:
        st.error("Invalid mode provided, supported - mode or config")
        return False
    del kwargs['mode']
    output = st.show(dut, command, type="click")
    st.debug(output)

    entries = utils.filter_and_select(output, None, kwargs)
    if not entries:
        return False

    return True
Exemple #2
0
def config_save(dut, shell='sonic', skip_error_check=True):
    """
    To perform config save.
    Author : Prudvi Mangadu ([email protected])

    :param dut: single or list of duts
    :return:
    """
    dut_li = list(dut) if isinstance(dut, list) else [dut]
    st.log("Performing config save")
    if shell == 'sonic':
        command = 'config save -y'
        [retvals, exceps] = utils.exec_foreach(True, dut_li, st.config,
                                               command)
    elif shell == "vtysh":
        command = 'do copy running-config startup-config'
        [retvals,
         exceps] = utils.exec_foreach(True,
                                      dut_li,
                                      st.config,
                                      command,
                                      type=shell,
                                      skip_error_check=skip_error_check)
    else:
        command = "do write memory"
        [retvals,
         exceps] = utils.exec_foreach(True,
                                      dut_li,
                                      st.config,
                                      command,
                                      type=shell,
                                      skip_error_check=skip_error_check)
    st.debug([retvals, exceps])
    return True
Exemple #3
0
def _get_rest_brief_dhcp_relay_data(dut, family='ipv4'):
    """
    To get the dhcp-relay brief data
    Author Jagadish Chatrasi ([email protected])
    :param dut:
    :param family:
    :return:
    """
    retval = list()
    rest_urls = st.get_datastore(dut, 'rest_urls')
    ip_string = '' if family == 'ipv4' else 'v6'
    output = get_interface_ip_address(dut, family=family)
    interfaces = {entry['interface'] for entry in output}
    interfaces.discard('eth0')
    for intf in interfaces:
        url = rest_urls['get_dhcp{}_relay_helper_address'.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:helper-address') and isinstance(out['output']['openconfig-relay-agent:helper-address'], list):
            addresses = out['output']['openconfig-relay-agent:helper-address']
            for address in addresses:
                temp = dict()
                temp['intf'] = intf
                temp['dhcprelay_addr'] = address
                retval.append(temp)
    st.debug(retval)
    return retval
Exemple #4
0
def verify_nat_entry_db(dut, table, prot, ip, port, **kwargs):
    """
    Author : Priyanka
    :param dut:
    :param table:
    :param prot:
    :param ip:
    :param port:
    :param kwargs:
    :return:
    """
    string = ''
    if table == "NAT_TABLE":
        string = "NAT_TABLE:{}".format(ip)
    elif table == "NAPT_TABLE":
        string = "NAPT_TABLE:{}:{}:{}".format(prot, ip, port)
    command = redis.build(dut, redis.APPL_DB, "hgetall {}".format(string))
    output = st.show(dut, command)
    st.debug(output)
    for each in kwargs.keys():
        match = {each: kwargs[each]}
        entries = filter_and_select(output, None, match)
        if not entries:
            st.log("{} and {} is not match ".format(each, kwargs[each]))
            return False
    return True
Exemple #5
0
def show_nat_config(dut, mode, **kwargs):
    """
    Verify NAT Config
    :param dut:
    :param mode:
    :param kwargs:
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    cli_type = "klish" if cli_type in ["rest-patch", "rest-put"] else cli_type
    nat_config_modes = ['globalvalues', 'static', 'pool', 'bindings']
    if mode not in nat_config_modes:
        st.error("Invalid mode {}".format(mode))
        return False
    command = "show nat config {}".format(mode)
    output = st.show(dut, command, type=cli_type)
    response = list()
    match = dict()
    for each in kwargs.keys():
        match.update({each: kwargs[each]})
    if match:
        entries = filter_and_select(output, None, match)
        if not entries:
            for each in kwargs.keys():
                st.log("{} and {} is not match ".format(each, kwargs[each]))
            return []
        st.debug(entries)
        if isinstance(entries, dict):
            response.append(entries)
            return response
        else:
            return entries
    return output
Exemple #6
0
def get_nat_translations(dut, **kwargs):
    """
    Get NAT Translations
    Author : Prudvi Mangadu ([email protected])

    :param dut:
    :return:
    """
    get_list = ["trn_src_ip", "trn_src_ip_port", "trn_dst_ip", "trn_dst_ip_port"]
    cli_type = st.get_ui_type(dut, **kwargs)
    output = show_nat_translations(dut, cli_type=cli_type)
    st.log(output)
    match = {}
    if 'protocol' in kwargs:
        match['protocol'] = kwargs['protocol']
    if 'src_ip' in kwargs:
        match['src_ip'] = kwargs['src_ip']
    if 'src_ip_port' in kwargs:
        match['src_ip_port'] = kwargs['src_ip_port']
    if 'dst_ip' in kwargs:
        match['dst_ip'] = kwargs['dst_ip']
    if 'dst_ip_port' in kwargs:
        match['dst_ip_port'] = kwargs['dst_ip_port']
    st.debug(match)
    entries = filter_and_select(output, get_list, match)
    return entries
def verify_stp_entry_db(dut, table, vlan = None, ifname = None, **kwargs):
   """
   """
   if table == "_STP_VLAN_INTF_TABLE":
      cmd = "Vlan"+str(vlan)
      string = "{}:{}:{}".format(table, cmd, ifname)
   elif table == "_STP_PORT_TABLE":
      string = "{}:{}".format(table, ifname)
   else:
      print("invalid table")
      return False

   print("string is-")
   print(string)

   command = redis.build(dut, redis.APPL_DB, "hgetall {}".format(string))
   print("command is -", command)

   output = st.show(dut, command)
   print("output is -")
   print(output)
   st.debug(output)

   print("kwargs: ", kwargs)

   for each in kwargs.keys():
      match = {each: kwargs[each]}
      entries = filter_and_select(output, None, match)
      print("match :", match)
      print("entries:", entries)
      if not entries:
         st.log("{} and {} do not match ".format(each, kwargs[each]))
         return False
   return True
Exemple #8
0
def copp_module_hooks(request):
    global vars, tg, tg_ph_1, d1_p1, hw_constants, deviation_percentage, d1_p1_mac, copp_data, vlan_igmp, copp_data_pir
    vars = st.ensure_min_topology("D1T1:1")
    hw_constants = st.get_datastore(vars.D1, "constants", "default")
    st.debug("hw_constants: {}".format(hw_constants))
    tg, tg_ph_1 = tgapi.get_handle_byname("T1D1P1")
    d1_p1 = vars.D1T1P1
    vlan_igmp = 3188
    vlan_obj.create_vlan(vars.D1, vlan_igmp)
    deviation_percentage = 0.05
    ret_val = copp_obj.get_copp_config(dut=vars.D1, table_name='all')
    if ret_val:
        copp_data = ret_val
    else:
        st.report_fail('module_config_failed',
                       'show copp config command failed')
    copp_data_pir = copp_obj.set_copp_pir_config(vars.D1, config='get')
    # Get the DUT mac address
    d1_p1_mac = basic_obj.get_ifconfig(vars.D1, d1_p1)[0]['mac']
    # Config the routing interface
    ip_obj.config_ip_addr_interface(dut=vars.D1,
                                    interface_name=d1_p1,
                                    ip_address='1.1.1.2',
                                    subnet='24')
    yield
    # Un-configure the routing interface
    ip_obj.delete_ip_interface(dut=vars.D1,
                               interface_name=d1_p1,
                               ip_address='1.1.1.2',
                               subnet='24')
    vlan_obj.delete_vlan(vars.D1, vlan_igmp)
Exemple #9
0
def rest_get_fallback_status(dut, portchannel):
    """
    Author: Jagadish Chatrasi ([email protected])
    :param dut:
    :type dut:
    :param portchannel:
    :type str:
    :return:
    :rtype:
    """
    rest_urls = st.get_datastore(dut, 'rest_urls')
    ret_val = []
    try:
        fallback_info = dict()
        url = rest_urls['fallback_oper_status_get'].format(portchannel)
        oper_info = get_rest(dut, rest_url=url)
        url = rest_urls['fallback_enable_config'].format(portchannel)
        enable_info = get_rest(dut, rest_url=url)
        fallback_info['port_channel_name'] = portchannel
        fallback_info['fallback_config'] = 'Enabled' if enable_info['output'][
            'openconfig-interfaces-ext:fallback'] else 'Disabled'
        fallback_info['fallback_oper_status'] = 'Enabled' if oper_info[
            'output']['openconfig-interfaces-ext:fallback'] else 'Disabled'
        ret_val.append(fallback_info)
        st.debug(ret_val)
        return ret_val
    except Exception as e:
        st.error("{} exception occurred".format(e))
        st.debug(ret_val)
        return ret_val
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
Exemple #11
0
def get_rest_server_info(server_output):
    ret_val = []
    try:
        servers = server_output["openconfig-system:server"]
        for server in servers:
            temp = dict()
            server_details = server['state']
            req_params = ['address', 'openconfig-system-ext:reach', 'openconfig-system-ext:now', 'stratum', 'openconfig-system-ext:peerdelay', 'openconfig-system-ext:peertype', 'openconfig-system-ext:peeroffset', 'openconfig-system-ext:peerjitter', 'poll-interval', 'openconfig-system-ext:refid', 'openconfig-system-ext:selmode']
            if all(param in server_details for param in req_params):
                temp['remote'] = str(server_details['openconfig-system-ext:selmode']+server_details['address'])
                temp['reach'] = str(server_details['openconfig-system-ext:reach'])
                temp['when'] = str(server_details['openconfig-system-ext:now'])
                temp['st'] = str(server_details['stratum'])
                temp['delay'] = str(server_details['openconfig-system-ext:peerdelay'])
                temp['t'] = str(server_details['openconfig-system-ext:peertype'])
                temp['offset'] = str(server_details['openconfig-system-ext:peeroffset'])
                temp['jitter'] = str(server_details['openconfig-system-ext:peerjitter'])
                temp['poll'] = str(server_details['poll-interval'])
                temp['refid'] = str(server_details['openconfig-system-ext:refid'])
                ret_val.append(temp)
        st.debug(ret_val)
        return ret_val
    except Exception as e:
        st.error("{} exception occurred".format(e))
        st.debug("Given data is: {}".format(server_output))
        return ret_val
Exemple #12
0
def verify_ntp_synch(dut, server):
    entries = show_ntp_server(dut)
    if filter_and_select(entries, None, {'remote': "*{}".format(server)}):
        st.debug("NTP synchronized with server: {}".format(server))
        return True
    st.error("NTP not synchronized with server: {}".format(server))
    return False
Exemple #13
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
Exemple #14
0
def verify_show_nat_config_static(dut, mode=None, **kwargs):
    """
    Author : Priyanka
    :param :dut:
    :param :mode:
    :param :local_ip:
    :param :global_ip:
    :param :nat_type:
    :param :twice_nat_id:
    :param :prot:
    :param :local_port:
    :param :global_port:
    """
    nat_config_modes = ['globalvalues', 'static', 'pool', 'bindings']
    if mode not in nat_config_modes:
        st.error("Invalid mode {}, should be in {}".format(mode, ','.join(nat_config_modes)))
        return False
    command = "show nat config {}".format(mode)
    output = st.show(dut, command)
    st.debug(output)
    for each in kwargs.keys():
        match = {each: kwargs[each]}
        entries = filter_and_select(output, None, match)
        if not entries:
            st.log("{} and {} is not match ".format(each, kwargs[each]))
            return False
    return True
Exemple #15
0
def rest_get_queue_counters(dut, port):
    """
    Author: Jagadish Chatrasi ([email protected])
    :param dut:
    :type dut:
    :param port:
    :type port:
    :return:
    :rtype:
    """
    ret_val = list()
    rest_urls = st.get_datastore(dut, 'rest_urls')
    url = rest_urls['queue_counters_get'].format(port)
    try:
        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(':')
            temp['port'] = port
            temp['txq'] = "{}{}".format(
                counters_info["openconfig-qos-ext:traffic-type"], queue)
            temp['pkts_drop'] = counters_info['dropped-pkts']
            temp['byte_drop'] = counters_info[
                'openconfig-qos-ext:dropped-octets']
            temp['pkts_count'] = counters_info['transmit-pkts']
            temp['byte_count'] = counters_info['transmit-octets']
            ret_val.append(temp)
        st.debug(ret_val)
        return ret_val
    except Exception as e:
        st.error("{} exception occurred".format(e))
        st.log("The output is:{}".format(get_info))
        st.debug(ret_val)
        return ret_val
Exemple #16
0
def apis_common_init(scope, ref=None):
    """

    :param scope:
    :type scope:
    :param ref:
    :type ref:
    :return:
    :rtype:
    """
    from spytest import st, utils
    if scope == "session":
        return _api_common_session_begin()

    if scope == "module":
        st.debug("---- common module {} begin ----".format(ref))
    elif scope == "function":
        st.debug("---- common test {} begin ----".format(ref))
        if not os.getenv("SPYTEST_SKIP_INIT_COMMANDS"):

            def f(dut):
                if st.get_device_type(dut) in ["sonic", "vsonic"]:
                    if not st.is_community_build():
                        st.show(dut,
                                "show system status",
                                skip_error_check=True,
                                skip_tmpl=True)

            utils.exec_foreach(True, st.get_dut_names(), f)
Exemple #17
0
def get_mac_entries_by_mac_address(dut, mac_address, **kwargs):
    '''
    Display MAC entries with a MAC search pattern and return the output.

    :param mac_address:
    :param cli_type:
    :return:
    '''
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type == 'click':
        command = "show mac | grep {}".format(mac_address)
        mac_entries = st.show(dut, command)
    elif cli_type == 'klish':
        command = "show mac address-table | grep {}".format(mac_address)
        mac_entries = st.show(dut, command, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        entries = get_mac(dut, cli_type=cli_type)
        st.debug(entries)
        mac_entries = []
        for entry in entries:
            exp = "^{}".format(mac_address.strip())
            if re.search(exp, entry['macaddress'], re.IGNORECASE):
                mac_entries.append(entry)
        st.debug(mac_entries)
    else:
        st.log("Unsupported cli")
        return False
    return mac_entries
Exemple #18
0
def verify_nat_translations(dut, **kwargs):
    """
    Verify NAT Translations
    Author : Prudvi Mangadu ([email protected])

    :param :dut:
    :param :protocol
    :param :src_ip
    :param :src_ip_port
    :param :dst_ip
    :param :dst_ip_port
    :param :trn_src_ip
    :param :trn_src_ip_port
    :param :trn_dst_ip
    :param :trn_dst_ip_port
    :return:
    """
    entries = None
    cli_type = st.get_ui_type(dut, **kwargs)
    output = show_nat_translations(dut, cli_type=cli_type)
    st.debug(output)
    for each in kwargs.keys():
        match = {each: kwargs[each]}
        get_list = ["trn_src_ip", "trn_src_ip_port", "trn_dst_ip", "trn_dst_ip_port"]
        entries = filter_and_select(output, get_list, match)
        if not entries:
            st.log("{} and {} is not match ".format(each, kwargs[each]))
            return False
    return entries
def show_threshold_breaches(dut, cli_type=""):
    """
    Show Threshold Breaches
    Author: Prudvi Mangadu ([email protected])

    :param dut:
    :cli_type
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if cli_type in ["click", "klish"]:
        command = "show threshold breaches"
        output = st.show(dut, command, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        output = list()
        url = st.get_datastore(dut, "rest_urls")["threshold_breaches"]
        try:
            get_resp = get_rest(dut, rest_url=url)["output"]["openconfig-qos-ext:threshold-breaches"]["breach"]
            for each in get_resp:
                breach = dict()
                if "state" in each:
                    breach["eventid"] = str(each["id"])
                    breach["index"] = str(each["state"]["index"])
                    breach["buffer"] = each["state"]["buffer"]
                    breach["threshold_type"] = each["state"]["type"]
                    breach["counter"] = each["state"]["counter"]
                    breach["value"] = str(each["state"]["breach-value"])
                    breach["port"] = each["state"]["port"]
                    output.append(breach)
        except Exception as e:
            st.debug("Error in getting threshold breaches")
            st.debug(e)
            return []
    return output
Exemple #20
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
Exemple #21
0
def rbac_module_epilog():
    sshapi.ssh_keygen(vars.D2, mode='destroy', path=rbac.client_keygen_path)
    rbac_config_user(1)
    rest_client_auth(vars.D1, auth_type='')
    gnmi_client_auth(vars.D1, auth_type='')
    password = st.get_credentials(vars.D1)[3]
    st.debug("The password for user: {} is: {}".format(
        rbac.default_user['username'], password))
Exemple #22
0
def verify_ip_in_network(ip_address, prefix):
    st.debug("IP ADDRESS : {}".format(ip_address))
    st.debug("NETWORK : {}".format(prefix))
    [prefix_address, net_size] = prefix.split("/")
    net_size = int(net_size)
    prefix_network = get_network_from_address(prefix_address, net_size)
    ip_network = get_network_from_address(ip_address, net_size)
    return ip_network == prefix_network
Exemple #23
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)
Exemple #24
0
def show_ztp_status(dut, expect_reboot=False, cli_type=""):
    """
    Author: Chaitanya Vella ([email protected])
    API to show ztp status
    :param dut:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    result = dict()
    cli_type = "klish" if cli_type in ["rest-put", "rest-patch"] else cli_type
    if cli_type not in ["click", "klish"]:
        st.error("UNSUPPORTED CLI TYPE")
        return result
    command = "sudo ztp status" if cli_type == "click" else "show ztp-status"
    output = st.show(dut, command, expect_reboot=False, type=cli_type)
    file_name = dict()
    timestamps = dict()
    #excluded_file_name = ["--sonic-mgmt--#"]
    if output:
        for row in output:
            result["filenames"] = list()
            result["timestamps"] = list()
            if result.get("service"):
                pass
            else:
                result["service"] = row.get("service", "")
            # if not result["source"]:
            if result.get("source"):
                pass
            else:
                result["source"] = row.get("source", "")
            # if not result["status"]:
            if result.get("status"):
                pass
            else:
                result["status"] = row.get("status", "")
            # if not result["adminmode"]:
            if result.get("adminmode"):
                pass
            else:
                result["adminmode"] = row.get("adminmode", "")
            # if not result["timestamp"]:
            result["timestamp"] = row.get("timestamp", "")
            if row.get("filename"):
                if cli_type == "click":
                    values = row["filename"].split(":")
                    file_name[values[0].strip()] = values[1].strip()
                    result["filenames"].append(file_name)
                elif cli_type == "klish":
                    file_name[row.get("filename")] = row.get("filestatus")
                    result["filenames"].append(file_name)
                    if row.get("filetimestamp"):
                        timestamps.update({row.get("filename"):row.get("filetimestamp")})
                        result["timestamps"].append(timestamps)
            # if not result["processingtext"]:
            # result["processingtext"] = row["processingtext"] if "processingtext" in row and row["processingtext"] else ""
    st.debug(result)
    return result
Exemple #25
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
def poll_verify_interface_ip_address(dut, interface_name, ip_address, loopCnt):
    iter = 1
    while True:
        out = ip_obj.get_interface_ip_address(dut, interface_name=interface_name, family="ipv6")
        st.debug("The ipv6 interface output is: {}".format(out))
        if out and out[0]['ipaddr'] in ip_address:
            return True
        if iter > loopCnt:
            return False
        iter = iter + 1
def bcm_cmd_l3_intf_show(dut, **kwargs):
    command = "bcmcmd 'l3 intf show'"
    output = st.show(dut, command)
    st.debug(output)
    for each in kwargs.keys():
        if utils.filter_and_select(output, None, {each: kwargs[each]}):
            st.error("No match for {} = {} in table".format(
                each, kwargs[each]))
            return False
    return True
Exemple #28
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)
Exemple #29
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
Exemple #30
0
def get_num_entries_error_db(dut, ifname_type=None):
    """
    To Get total entries in Error Database using redis cli
    :param dut:
    :return:
    """
    command = redis.build(dut, redis.ERROR_DB, "keys ERROR.*")
    output = st.show(dut, command)
    output = _get_entries_with_native_port(dut, output, ifname_type=ifname_type)
    st.debug(output)
    return len(output)