def check_for_error(rest_url, response, negative=True):
    st.log("RESPONSE : {}".format(response))
    if response:
        if negative:
            if not rest_status(response["status"]):
                st.log("Observed {} code in REST response".format(
                    response["status"]))
                st.report_fail("rest_error_observed", response["status"])
        else:
            if rest_status(response["status"]):
                st.log("Observed {} code in REST response".format(
                    response["status"]))
                st.report_fail("rest_error_observed", response["status"])
        if response["status"] == 400:
            output = json.loads(response["output"])
            if output["ietf-restconf:errors"]["error"][0][
                    "error-type"] != "protocol":
                st.report_fail("ocyang_error_is_not_as_per_the_design", "TYPE")
            elif output["ietf-restconf:errors"]["error"][0][
                    "error-tag"] != "operation-not-supported":
                st.report_fail("ocyang_error_is_not_as_per_the_design", "TAG")
            elif "Unsupported client version" not in output[
                    "ietf-restconf:errors"]["error"][0]["error-message"]:
                st.report_fail("ocyang_error_is_not_as_per_the_design",
                               "MESSAGE")
    else:
        st.report_fail("no_response_found", rest_url)
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
示例#3
0
def delete_vlan(dut, vlan_list, cli_type=''):
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    """
    To delete list of VLANs.
    Author : Prudvi Mangadu ([email protected])

    :param dut:
    :param vlan_list:
    :param cli_type:
    :return:
    """

    st.log("Delete vlan")
    vlan_li = map(str, vlan_list) if isinstance(vlan_list,
                                                list) else [vlan_list]
    commands = list()
    rest_fail_status = False
    try:
        for each_vlan in vlan_li:
            if cli_type == "click":
                commands.append("config vlan del {}".format(each_vlan))
            elif cli_type == "klish":
                commands.append("no interface Vlan {}".format(each_vlan))
            elif cli_type in ["rest-put", "rest-patch"]:
                rest_url = st.get_datastore(
                    dut, "rest_urls")["per_interface_details"].format(
                        "Vlan{}".format(each_vlan))
                output = delete_rest(dut, rest_url=rest_url, get_response=True)
                if not output:
                    st.error("OUTPUT IS EMPTY FROM DELETE VLAN REST CALL")
                    return False
                st.log("STATUS: {}".format(output["status"]))
                if not rest_status(output["status"]):
                    rest_fail_status = True
            else:
                st.log("Unsupported CLI type")
                return False
        if rest_fail_status:
            st.log("One of VLAN DELETE REST call failed")
            return False
        if commands:
            response = st.config(dut,
                                 commands,
                                 skip_error_check=True,
                                 type=cli_type)
            if "Error" in response:
                st.log(response)
                return False
            else:
                vlan_list = get_vlan_list(dut, cli_type=cli_type)
                for each_vlan in vlan_li:
                    if each_vlan in vlan_list:
                        st.error(" Vlan{} is not deleted".format(each_vlan))
                        return False
        return True
    except Exception as e1:
        st.log(e1)
        st.error(" Vlan is not deleted due to other reasons")
        return False
def get_version(dut):
    rest_url = "{}ietf-yang-library:modules-state/module-set-id".format(
        oc_yang_data.base_url)
    headers = {"accept": "application/yang-data+json"}
    response = rest_call(dut,
                         headers=headers,
                         username=oc_yang_data.username,
                         password=oc_yang_data.password,
                         url=rest_url,
                         call_type='get',
                         port="")
    st.log(response)
    if response:
        if not rest_status(response["status"]):
            st.log("Observed {} code in REST response".format(
                response["status"]))
            st.report_fail("rest_error_observed", response["status"])
        return json.loads(
            response["output"])["ietf-yang-library:module-set-id"]
    else:
        st.report_fail("no_response_found", rest_url)
示例#5
0
def show_vlan_brief(dut, vlan_id=None, cli_type=''):
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    """
    To get vlan config from 'show vlan brief'
    Author : Prudvi Mangadu ([email protected])

    :param dut:
    :param vlan_id:
    :param cli_type:
    :return:
    """
    if cli_type == "click":
        st.log("show vlan brief")
        command = "show vlan brief"
    elif cli_type == "klish":
        command = "show Vlan"
        if vlan_id:
            command += " {}".format(vlan_id)
    elif cli_type in ["rest-put", "rest-patch"]:
        rest_url = st.get_datastore(dut, "rest_urls")["config_interface"]
        get_resp = get_rest(dut, rest_url=rest_url, timeout=600)
        if get_resp and rest_status(get_resp["status"]):
            vlan_data = show_vlan_from_rest_response(get_resp["output"])
            if not vlan_id:
                return vlan_data
            else:
                filter_vlan_data = list()
                for vlans in vlan_data:
                    if str(vlans["vid"].replace("Vlan", "")) == vlan_id:
                        filter_vlan_data.append(vlans)
                return filter_vlan_data
        else:
            return []
    else:
        st.log("Unsupported CLI type")
        return False

    return st.show(dut, command, type=cli_type)
示例#6
0
def delete_vlan_member(dut,
                       vlan,
                       port_list,
                       tagging_mode=False,
                       cli_type='',
                       skip_error_check=False):
    """
    Delete Members in VLAN
    Author : Prudvi Mangadu ([email protected])
    :param dut:
    :param vlan:
    :param port_list:
    :param participation_mode:
    :param cli_type:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    st.log("Delete member {} from the VLAN {}".format(port_list, vlan))
    if tagging_mode:
        participation_mode = "trunk"
    else:
        participation_mode = "access"
    port_li = make_list(port_list)
    commands = list()
    rest_fail_status = False
    for each_port in port_li:
        if cli_type == "click":
            command = "config vlan member del {} {}".format(vlan, each_port)
            out = st.config(dut, command, skip_error_check=skip_error_check)
            if "is not a member of Vlan{}".format(vlan) in out:
                st.error("{} is not a member of Vlan{}".format(
                    each_port, vlan))
                return False
            if "Vlan{} doesn't exist".format(vlan) in out:
                st.error("Vlan{} doesn't exist".format(vlan))
                return False
        elif cli_type == "klish":
            interface_details = get_interface_number_from_name(each_port)
            if not interface_details:
                st.log(
                    "Interface details not found {}".format(interface_details))
                return False
            commands.append("interface {} {}".format(
                interface_details.get("type"),
                interface_details.get("number")))
            if participation_mode == "trunk":
                command = "switchport trunk allowed Vlan remove {}".format(
                    vlan)
                commands.append("{}".format(command))
            elif participation_mode == "access":
                command = "switchport access Vlan"
                commands.append("no {}".format(command))
            commands.append("exit")
        elif cli_type in ["rest-put", "rest-patch"]:
            if participation_mode == "access":
                if "Eth" in get_interface_number_from_name(each_port)["type"]:
                    rest_url = st.get_datastore(
                        dut,
                        "rest_urls")["interface_access_member_config"].format(
                            each_port)
                else:
                    rest_url = st.get_datastore(
                        dut,
                        "rest_urls")["aggregate_access_member_config"].format(
                            each_port)
            else:
                vlan_id = str(vlan).split('-')
                vlan = '{}..{}'.format(
                    vlan_id[0], vlan_id[1]) if len(vlan_id) > 1 else vlan
                if "Eth" in get_interface_number_from_name(each_port)["type"]:
                    rest_url = st.get_datastore(
                        dut,
                        "rest_urls")["interface_trunk_member_config"].format(
                            each_port, vlan)
                else:
                    rest_url = st.get_datastore(
                        dut,
                        "rest_urls")["aggregate_trunk_member_config"].format(
                            each_port, vlan)
            output = delete_rest(dut, rest_url=rest_url, get_response=True)
            if not output:
                st.error("OUTPUT IS EMPTY FROM DELETE VLAN MEMBER REST CALL")
                return False
            st.log("STATUS: {}".format(output["status"]))
            if not rest_status(output["status"]):
                rest_fail_status = True
        else:
            st.error("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
            return False
    if rest_fail_status:
        st.log("One of VLAN member DELETE REST call failed")
        return False
    if commands:
        st.config(dut,
                  commands,
                  type=cli_type,
                  skip_error_check=skip_error_check)
    return True
示例#7
0
def show_session_all(dut, session_name=None, cli_type=""):
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    """
    API to show the mirror session output for both erspan and span
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :param session_name:
    :return:
    {'span': [{u'source_port': 'Ethernet4', u'direction': 'INGRESS', u'span_name': 'portmir0',
    u'destination_port': 'Ethernet0', u'span_status': 'active'},
    {u'source_port': 'Ethernet84', u'direction': 'INGRESS', u'span_name': 'portmir3',
    u'destination_port': 'Ethernet5', u'span_status': 'active'}],
    'erspan': [{u'status': 'active', u'queue': '', u'name': 'everflow0', u'dscp': '78',
    u'src_ip': '10.1.0.32', u'ttl': '', u'dst_ip': '10.0.0.7', u'gre_type': '0x866'},
    {u'status': 'active', u'queue': '', u'name': 'everflow0', u'dscp': '64', u'src_ip': '10.1.0.33',
    u'ttl': '', u'dst_ip': '10.0.0.7', u'gre_type': '0x866'}]}

    """
    result = dict()
    erspan_cols = [
        "name", "status", "src_ip", "dst_ip", "gre_type", "dscp", "ttl",
        "queue", "policer", "erspan_src_port", "erspan_direction"
    ]
    span_cols = [
        "span_name", "span_status", "destination_port", "source_port",
        "direction"
    ]
    if cli_type == "click":
        command = "show mirror_session"
        if session_name:
            command += " {}".format(session_name)
        output = st.show(dut, command, type=cli_type)
    elif cli_type == "klish":
        command = "show mirror-session"
        if session_name:
            command += " {}".format(session_name)
        output = st.show(dut, command, type=cli_type)
    elif cli_type in ["rest-put", "rest-patch"]:
        output = []
        rest_urls = st.get_datastore(dut, "rest_urls")
        if not session_name:
            url = rest_urls['get_session_all']
            rest_get_output = get_rest(dut, rest_url=url)
            if rest_get_output and rest_get_output.get(
                    "output") and rest_status(rest_get_output["status"]):
                actual_data = rest_get_output['output'][
                    'openconfig-mirror-ext:mirror']['sessions']['session']
                for i in actual_data:
                    process_data = i['state']
                    rest_out_keys = process_data.keys()
                    if 'dscp' in rest_out_keys:
                        temp1 = {}
                        temp1['name'] = i['name']
                        temp1['erspan_direction'] = i['state'][
                            'direction'] if 'direction' in i['state'] else ''
                        temp1['erspan_src_port'] = i['state'][
                            'src-port'] if 'src-port' in i['state'] else ''
                        temp1['dscp'] = i['state']['dscp'] if 'dscp' in i[
                            'state'] else ''
                        temp1['dst_ip'] = str(
                            i['state']
                            ['dst-ip']) if 'dst-ip' in i['state'] else ''
                        temp1['queue'] = str(i['state']['queue']
                                             ) if 'queue' in i['state'] else ''
                        temp1['src_ip'] = i['state'][
                            'src-ip'] if 'src-ip' in i['state'] else ''
                        temp1['gre_type'] = i['state'][
                            'gre-type'] if 'gre-type' in i['state'] else ''
                        temp1['ttl'] = str(
                            i['state']['ttl']) if 'ttl' in i['state'] else ''
                        temp1['span_name'] = temp1['direction'] = temp1[
                            'source_port'] = temp1['destination_port'] = ''
                        url = rest_urls['get_mirror_status'].format(i['name'])
                        status_out = get_rest(dut, rest_url=url)
                        temp1['status'] = status_out['output'][
                            'openconfig-mirror-ext:status']
                        output.append(temp1)
                    else:
                        temp2 = {}
                        temp2['span_name'] = i['name']
                        temp2['direction'] = i['state'][
                            'direction'] if 'direction' in i['state'] else ''
                        temp2['source_port'] = i['state'][
                            'src-port'] if 'src-port' in i['state'] else ''
                        temp2['destination_port'] = i['state'][
                            'dst-port'] if 'dst-port' in i['state'] else ''
                        temp2['name'] = temp2['erspan_direction'] = temp2['erspan_src_port'] = temp2['dscp'] = temp2[
                            'dst_ip'] = temp2['queue'] \
                            = temp2['src_ip'] = temp2['gre_type'] = temp2['ttl'] = ''
                        url = rest_urls['get_mirror_status'].format(i['name'])
                        status_out = get_rest(dut, rest_url=url)
                        temp2['span_status'] = status_out['output'][
                            'openconfig-mirror-ext:status']
                        output.append(temp2)
        if session_name:
            url = rest_urls['get_session_session_name'].format(session_name)
            rest_get_output = get_rest(dut, rest_url=url)
            if rest_get_output and rest_get_output.get(
                    "output") and rest_status(rest_get_output["status"]):
                actual_data = rest_get_output['output'][
                    'openconfig-mirror-ext:session'][0]
                temp = {}
                process_data = actual_data['state']
                rest_out_keys = process_data.keys()
                st.log("getting mirror status")
                url = rest_urls['get_mirror_status'].format(session_name)
                status_out = get_rest(dut, rest_url=url)
                if 'dscp' in rest_out_keys:
                    if 'dscp' in erspan_cols:
                        temp['name'] = actual_data['name']
                        temp['erspan_direction'] = actual_data['state'][
                            'direction'] if 'direction' in actual_data[
                                'state'] else ''
                        temp['erspan_src_port'] = actual_data['state'][
                            'src-port'] if 'src-port' in actual_data[
                                'state'] else ''
                        temp['dscp'] = str(
                            actual_data['state']
                            ['dscp']) if 'dscp' in actual_data['state'] else ''
                        temp['dst_ip'] = actual_data['state'][
                            'dst-ip'] if 'dst-ip' in actual_data[
                                'state'] else ''
                        temp['queue'] = str(
                            actual_data['state']['queue']
                        ) if 'queue' in actual_data['state'] else ''
                        temp['src_ip'] = actual_data['state'][
                            'src-ip'] if 'src-ip' in actual_data[
                                'state'] else ''
                        temp['gre_type'] = actual_data['state'][
                            'gre-type'] if 'gre-type' in actual_data[
                                'state'] else ''
                        temp['ttl'] = str(
                            actual_data['state']
                            ['ttl']) if 'ttl' in actual_data['state'] else ''
                        temp['span_name'] = temp['direction'] = temp[
                            'source_port'] = temp['destination_port'] = ''
                        temp['status'] = status_out['output'][
                            'openconfig-mirror-ext:status']
                        output.append(temp)
                else:
                    temp['span_name'] = actual_data['name']
                    temp['direction'] = actual_data['state'][
                        'direction'] if 'direction' in actual_data[
                            'state'] else ''
                    temp['source_port'] = actual_data['state'][
                        'src-port'] if 'src-port' in actual_data[
                            'state'] else ''
                    temp['destination_port'] = actual_data['state'][
                        'dst-port'] if 'dst-port' in actual_data[
                            'state'] else ''
                    temp['name']=temp['erspan_direction']=temp['erspan_src_port']=temp['dscp']=temp['dst_ip']=temp['queue']\
                        = temp['src_ip'] = temp['gre_type']=temp['ttl'] = ''
                    temp['span_status'] = status_out['output'][
                        'openconfig-mirror-ext:status']
                    output.append(temp)
    if output:
        result["erspan"] = list()
        result["span"] = list()
        for data in output:
            erspan_dict = dict()
            span_dict = dict()
            for key, value in data.items():
                if data["name"] and key in erspan_cols:
                    erspan_dict[key] = value
                if data["span_name"] and key in span_cols:
                    span_dict[key] = value
            if span_dict:
                result["span"].append(span_dict)
            if erspan_dict:
                result["erspan"].append(erspan_dict)
    return result
示例#8
0
def clear_qos_map_table(dut, qos_maps, **kwargs):
    """
    Author: Jagadish Chatrasi ([email protected])
    To clear qos map table
    :param dut:
    :type dut:
    :param qos_maps:
    :type qos_maps:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    qos_maps = make_list(qos_maps)
    qos_clear = kwargs.get('qos_clear', False)
    skip_error = kwargs.get('skip_error', False)
    error_msg = kwargs.get('error_msg', False)
    errors = make_list(error_msg) if error_msg else errors_list
    if (not qos_clear) and cli_type == 'click':
        cli_type = 'klish'
    if cli_type == 'click':
        command = 'config qos clear'
        response = st.config(dut,
                             command,
                             type=cli_type,
                             skip_error_check=skip_error)
        if any(error.lower() in response.lower() for error in errors):
            st.error("The response is: {}".format(response))
            return False
    elif cli_type == 'klish':
        commands = list()
        for qos_map in qos_maps:
            commands_map = {
                'dot1p_to_tc_map': "no qos map dot1p-tc {}",
                'dscp_to_tc_map': "no qos map dscp-tc {}",
                'pfc_to_queue_map': "no qos map pfc-priority-queue {}",
                'tc_to_dot1p_map': "no qos map tc-dot1p {}",
                'tc_to_dscp_map': "no qos map tc-dscp {}",
                'tc_to_pg_map': "no qos map tc-pg {}",
                'tc_to_queue_map': "no qos map tc-queue {}"
            }
            if qos_map['map'] in commands_map:
                commands.append(commands_map[qos_map['map']].format(
                    qos_map['obj_name']))
            else:
                st.error('Invalid map type: {}'.format(qos_map['map']))
                return False
        response = st.config(dut,
                             commands,
                             type=cli_type,
                             skip_error_check=skip_error)
        if any(error.lower() in response.lower() for error in errors):
            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 qos_map in qos_maps:
            urls_map = {
                'dot1p_to_tc_map': rest_urls['dot1p_tc_table_config'],
                'dscp_to_tc_map': rest_urls['dscp_tc_table_config'],
                'pfc_to_queue_map':
                rest_urls['pfc_priority_queue_table_config'],
                'tc_to_dot1p_map': rest_urls['tc_dot1p_table_config'],
                'tc_to_dscp_map': rest_urls['tc_dscp_table_config'],
                'tc_to_pg_map': rest_urls['tc_pg_table_config'],
                'tc_to_queue_map': rest_urls['tc_queue_table_config']
            }
            if qos_map['map'] in urls_map:
                url = urls_map[qos_map['map']].format(qos_map['obj_name'])
            else:
                st.error('Invalid map type: {}'.format(qos_map['map']))
                return False
            if skip_error:
                out = delete_rest(dut, rest_url=url, get_response=True)
                error_resp = str(out['output']).lower()
                if ((not rest_status(int(out['status'])))
                        and any(error.lower() in error_resp
                                for error in errors)):
                    st.error("Failed clear {} table: {}".format(
                        qos_map['map'], qos_map['obj_name']))
                    return False
            else:
                if not delete_rest(dut, rest_url=url):
                    st.error("Failed clear {} table: {}".format(
                        qos_map['map'], qos_map['obj_name']))
                    return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True