Beispiel #1
0
def send_recv_eth(ptfadapter, source_ports, source_mac, dest_ports, dest_mac, src_vlan, dst_vlan):
    """
    send ethernet packet and verify it on dest_port
    :param ptfadapter: PTF adapter object
    :param source_port: source port
    :param source_mac: source MAC
    :param dest_port: destination port to receive packet on
    :param dest_mac: destination MAC
    :param vlan_id: VLAN id
    :return:
    """
    pkt = simple_eth_packet(
        eth_dst=dest_mac,
        eth_src=source_mac,
        vlan_vid=src_vlan
    )
    exp_pkt = simple_eth_packet(
        eth_dst=dest_mac,
        eth_src=source_mac,
        vlan_vid=dst_vlan
    )
    if dst_vlan:
        # expect to receive tagged packet:
        # sonic device might modify the 802.1p field,
        # need to use Mask to ignore the priority field.
        exp_pkt = Mask(exp_pkt)
        exp_pkt.set_do_not_care_scapy(scapy.Dot1Q, "prio")
    logger.debug('send packet src port {} smac: {} dmac: {} vlan: {} verifying on dst port {}'.format(
        source_ports, source_mac, dest_mac, src_vlan, dest_ports))
    testutils.send(ptfadapter, source_ports[0], pkt)
    testutils.verify_packet_any_port(ptfadapter, exp_pkt, dest_ports, timeout=FDB_WAIT_EXPECTED_PACKET_TIMEOUT)
Beispiel #2
0
def test_decap_standby_tor(apply_standby_state_to_orchagent,
                           build_encapsulated_packet, rand_selected_interface,
                           ptfadapter, tbinfo, rand_selected_dut,
                           tunnel_traffic_monitor):
    def verify_downstream_packet_to_server(ptfadapter, port, exp_pkt):
        """Verify packet is passed downstream to server."""
        packets = ptfadapter.dataplane.packet_queues[(0, port)]
        for packet in packets:
            if exp_pkt.pkt_match(packet):
                return True
        return False

    tor = rand_selected_dut
    encapsulated_packet = build_encapsulated_packet
    iface, _ = rand_selected_interface

    exp_ptf_port_index = get_ptf_server_intf_index(tor, tbinfo, iface)
    exp_pkt = build_expected_packet_to_server(encapsulated_packet)

    ptf_t1_intf = random.choice(get_t1_ptf_ports(tor, tbinfo))
    logging.info("send encapsulated packet from ptf t1 interface %s",
                 ptf_t1_intf)
    with tunnel_traffic_monitor(tor, existing=False):
        testutils.send(ptfadapter,
                       int(ptf_t1_intf.strip("eth")),
                       encapsulated_packet,
                       count=10)
        time.sleep(2)
        verify_downstream_packet_to_server(ptfadapter, exp_ptf_port_index,
                                           exp_pkt)
Beispiel #3
0
    def _verify_acl_traffic(self, setup, direction, ptfadapter, pkt, dropped,
                            ip_version):
        exp_pkt = self.expected_mask_routed_packet(pkt, ip_version)

        if ip_version == "ipv4":
            downstream_dst_port = DOWNSTREAM_IP_PORT_MAP.get(
                pkt[packet.IP].dst)
        else:
            downstream_dst_port = DOWNSTREAM_IP_PORT_MAP.get(
                pkt[packet.IPv6].dst)
        ptfadapter.dataplane.flush()
        testutils.send(ptfadapter, self.src_port, pkt)
        if direction == "uplink->downlink" and downstream_dst_port:
            if dropped:
                testutils.verify_no_packet(ptfadapter, exp_pkt,
                                           downstream_dst_port)
            else:
                testutils.verify_packet(ptfadapter, exp_pkt,
                                        downstream_dst_port)
        else:
            if dropped:
                testutils.verify_no_packet_any(ptfadapter,
                                               exp_pkt,
                                               ports=self.get_dst_ports(
                                                   setup, direction))
            else:
                testutils.verify_packet_any_port(ptfadapter,
                                                 exp_pkt,
                                                 ports=self.get_dst_ports(
                                                     setup, direction),
                                                 timeout=20)
Beispiel #4
0
 def verify_traffic(duthost,
                    connection,
                    route,
                    is_duthost_active=True,
                    is_route_existed=True):
     prefix = ipaddress.ip_network(route["prefix"])
     dst_host = str(random.choice(list(prefix.hosts())))
     pkt, exp_pkt = build_packet_to_server(duthost, ptfadapter, dst_host)
     ptf_t1_intf = random.choice(get_t1_ptf_ports(duthost, tbinfo))
     ptf_t1_intf_index = int(ptf_t1_intf.strip("eth"))
     is_tunnel_traffic_existed = is_route_existed and not is_duthost_active
     is_server_traffic_existed = is_route_existed and is_duthost_active
     tunnel_monitor = tunnel_traffic_monitor(
         duthost, existing=is_tunnel_traffic_existed)
     server_traffic_monitor = ServerTrafficMonitor(
         duthost,
         ptfhost,
         vmhost,
         tbinfo,
         connection["test_intf"],
         conn_graph_facts,
         exp_pkt,
         existing=is_server_traffic_existed)
     with tunnel_monitor, server_traffic_monitor:
         testutils.send(ptfadapter, ptf_t1_intf_index, pkt, count=10)
Beispiel #5
0
def test_decap_active_tor(build_encapsulated_packet, request, ptfhost,
                          rand_selected_interface, ptfadapter, tbinfo,
                          rand_selected_dut, tunnel_traffic_monitor):
    @contextlib.contextmanager
    def stop_garp(ptfhost):
        """Temporarily stop garp service."""
        ptfhost.shell("supervisorctl stop garp_service")
        yield
        ptfhost.shell("supervisorctl start garp_service")

    if is_t0_mocked_dualtor(tbinfo):
        request.getfixturevalue('apply_active_state_to_orchagent')
    else:
        request.getfixturevalue(
            'toggle_all_simulator_ports_to_rand_selected_tor')

    tor = rand_selected_dut
    encapsulated_packet = build_encapsulated_packet
    iface, _ = rand_selected_interface

    exp_ptf_port_index = get_ptf_server_intf_index(tor, tbinfo, iface)
    exp_pkt = build_expected_packet_to_server(encapsulated_packet,
                                              decrease_ttl=True)

    ptf_t1_intf = random.choice(get_t1_ptf_ports(tor, tbinfo))
    logging.info("send encapsulated packet from ptf t1 interface %s",
                 ptf_t1_intf)
    with stop_garp(ptfhost):
        ptfadapter.dataplane.flush()
        testutils.send(ptfadapter, int(ptf_t1_intf.strip("eth")),
                       encapsulated_packet)
        testutils.verify_packet(ptfadapter,
                                exp_pkt,
                                exp_ptf_port_index,
                                timeout=10)
Beispiel #6
0
def generate_and_verify_traffic(duthost1,
                                duthost2,
                                ptfadapter,
                                ptfhost,
                                src_port,
                                dst_ip,
                                router_mac,
                                get_routes,
                                collect,
                                down_link_on_dut=None,
                                pkt_action=ACTION_FORWARD):
    """
    Generate traffic, send and verify it
    Args:
        duthost1: DUT host object
        duthost2: DUT host object
        ptfadapter: PTF adapter
        ptfhost: PTF host object
        src_port: Source port from which pkt will be sent
        dst_ip: Destination ip address
        get_routes: Dict with routes for each DUT
        collect: Fixture which collects main info about link connection
        down_link_on_dut: Name of DUT on which link is down
        pkt_action: Action to verify, forward or drop
    """
    router1_mac = duthost1.facts["router_mac"]
    router2_mac = duthost2.facts["router_mac"]
    dst_ports = get_dst_port(duthost1, duthost2, get_routes, dst_ip, collect)
    src_port = get_port_number(ptfhost, src_port)
    pkt = craft_pkt(ptfadapter, router_mac, src_port, dst_ip)
    expected_src_mac = router1_mac if dst_ports == collect[
        duthost1.hostname]['vm_link_on_ptf'] else router2_mac

    exp_pkt = pkt.copy()
    if down_link_on_dut:
        exp_ttl = predict_exp_ttl(duthost1, duthost2, dst_ip, down_link_on_dut)
        exp_pkt[packet.IP].ttl = exp_ttl
    exp_pkt[packet.Ether].src = unicode(expected_src_mac)

    exp_pkt = mask.Mask(exp_pkt)
    exp_pkt.set_do_not_care_scapy(packet.Ether, "dst")
    exp_pkt.set_do_not_care_scapy(packet.IP, "id")
    exp_pkt.set_do_not_care_scapy(packet.IP, "chksum")
    exp_pkt.set_do_not_care_scapy(packet.TCP, "chksum")
    if not down_link_on_dut:
        exp_pkt.set_do_not_care_scapy(packet.IP, "ttl")

    ptfadapter.dataplane.flush()
    time.sleep(2)

    logger.info(
        "Sending pkt from port {} to dst_ip = {}, expected dst_port = {}".
        format(src_port, dst_ip, dst_ports))
    logger.info(pkt.sprintf("%Ether.src% %IP.src% -> %Ether.dst% %IP.dst%"))
    testutils.send(ptfadapter, src_port, pkt)

    if pkt_action == ACTION_FORWARD:
        testutils.verify_packet(ptfadapter, exp_pkt, dst_ports)
    elif pkt_action == ACTION_DROP:
        testutils.verify_no_packet(ptfadapter, exp_pkt, dst_ports)
Beispiel #7
0
def run_test_ipv4(ptfadapter, gather_facts):
    logger.info("Running test with ipv4 packets")
    dst_host_ipv4 = str(
        ip_address(unicode(gather_facts['dst_router_ipv4'])) + 1)
    pkt = testutils.simple_udp_packet(eth_dst=gather_facts['src_router_mac'],
                                      eth_src=gather_facts['src_host_mac'],
                                      ip_src=dst_host_ipv4,
                                      ip_dst=dst_host_ipv4,
                                      ip_ttl=DEFAULT_HLIM_TTL)
    logger.info("\nSend Packet:\neth_dst: {}, eth_src: {}, ipv6 ip: {}".format(
        gather_facts['src_router_mac'], gather_facts['src_host_mac'],
        dst_host_ipv4))

    testutils.send(ptfadapter, int(gather_facts['src_port_ids'][0]), pkt)

    pkt = testutils.simple_udp_packet(eth_dst=gather_facts['dst_host_mac'],
                                      eth_src=gather_facts['dst_router_mac'],
                                      ip_src=dst_host_ipv4,
                                      ip_dst=dst_host_ipv4,
                                      ip_ttl=DEFAULT_HLIM_TTL - 1)
    logger.info(
        "\nExpect Packet:\neth_dst: {}, eth_src: {}, ipv6 ip: {}".format(
            gather_facts['dst_host_mac'], gather_facts['dst_router_mac'],
            dst_host_ipv4))

    port_list = [int(port) for port in gather_facts['dst_port_ids']]
    testutils.verify_packet_any_port(ptfadapter,
                                     pkt,
                                     port_list,
                                     timeout=WAIT_EXPECTED_PACKET_TIMEOUT)
Beispiel #8
0
    def test_swap_labelstack(self, setup, ptfadapter):
        """ test swap labelstack """

        dst_pid = setup['dst_pid']
        src_pid = setup['src_pid']

        self.config_interface_mpls(setup, LABEL_SWAP_ROUTES)

        time.sleep(2)

        pkt = self.mpls_stack_packet(setup, ptfadapter)
        exp_pkt = self.expected_mask_mpls_swap_packet(pkt, 1000002)

        ptfadapter.dataplane.flush()
        testutils.send(ptfadapter, src_pid, pkt)

        try:
            res = testutils.verify_packet_any_port(ptfadapter,
                                                   exp_pkt,
                                                   ports=[dst_pid])
            logger.info(res)
        except Exception as e:
            self.teardown_labels(setup)
            pytest.fail('MPLS swap labelstack test failed \n' + str(e))

        self.teardown_labels(setup)
def send_and_verify_traffic(ptfadapter,
                            pkt,
                            exp_pkt,
                            src_port,
                            dst_port,
                            pkt_action=ACTION_FORWARD):
    """
    Send traffic and verify that traffic was received

    Args:
        ptfadapter: PTF adapter
        pkt: Packet that should be sent
        exp_pkt: Expected packet
        src_port: Source port
        dst_port: Destination port
        pkt_action: Packet action (forward or drop)
    """

    ptfadapter.dataplane.flush()
    logger.info("Send packet from port {} to port {}".format(
        src_port, dst_port))
    testutils.send(ptfadapter, src_port, pkt)

    if pkt_action == ACTION_FORWARD:
        testutils.verify_packet(ptfadapter, exp_pkt, dst_port)
    elif pkt_action == ACTION_DROP:
        testutils.verify_no_packet(ptfadapter, exp_pkt, dst_port)
def send_and_verify_packet(ptfadapter, packet, expected_packet, tx_port, rx_ports, exp_recv):
    ptfadapter.dataplane.flush()
    testutils.send(ptfadapter, pkt=packet, port_id=tx_port)
    if exp_recv:
        testutils.verify_packet_any_port(ptfadapter, pkt=expected_packet, ports=rx_ports, timeout=5)
    else:
        testutils.verify_no_packet_any(ptfadapter, pkt=expected_packet, ports=rx_ports)
Beispiel #11
0
    def test_push_label(self, setup, ptfadapter):
        """ test push label """

        dst_pid = setup['dst_pid']
        src_pid = setup['src_pid']

        self.config_interface_mpls(setup, LABEL_PUSH_ROUTES)

        time.sleep(2)

        pkt = self.icmp_packet(setup, ptfadapter)
        epkt = pkt.copy()
        pkt1 = epkt['IP']
        epkt['Ethernet'].type = 0x8847
        epkt['Ethernet'].remove_payload()
        mp = MPLS(label=1000002, s=1, ttl=255)
        mp.remove_payload()
        epkt /= mp
        epkt /= pkt1
        exp_pkt = self.expected_mask_mpls_push_packet(epkt, 1000001)

        ptfadapter.dataplane.flush()
        testutils.send(ptfadapter, src_pid, pkt)

        try:
            res = testutils.verify_packet_any_port(ptfadapter,
                                                   exp_pkt,
                                                   ports=[dst_pid])
            logger.info(res)
        except Exception as e:
            self.teardown_labels(setup)
            pytest.fail('MPLS push test failed \n' + str(e))

        self.teardown_labels(setup)
Beispiel #12
0
def generate_and_verify_traffic(duthost, ptfadapter, ip_dst, expected_ports, ipv6=False):
    if ipv6:
        pkt = testutils.simple_tcpv6_packet(
            eth_dst=duthost.facts["router_mac"],
            eth_src=ptfadapter.dataplane.get_mac(0, 0),
            ipv6_src='2001:db8:85a3::8a2e:370:7334',
            ipv6_dst=ip_dst,
            ipv6_hlim=64,
            tcp_sport=1234,
            tcp_dport=4321)
    else:
        pkt = testutils.simple_tcp_packet(
            eth_dst=duthost.facts["router_mac"],
            eth_src=ptfadapter.dataplane.get_mac(0, 0),
            ip_src='1.1.1.1',
            ip_dst=ip_dst,
            ip_ttl=64,
            tcp_sport=1234,
            tcp_dport=4321)

    exp_pkt = pkt.copy()
    exp_pkt = mask.Mask(exp_pkt)
    exp_pkt.set_do_not_care_scapy(packet.Ether, 'dst')
    exp_pkt.set_do_not_care_scapy(packet.Ether, 'src')
    if ipv6:
        exp_pkt.set_do_not_care_scapy(packet.IPv6, 'hlim')
        exp_pkt.set_do_not_care_scapy(packet.IPv6, 'chksum')
    else:
        exp_pkt.set_do_not_care_scapy(packet.IP, 'ttl')
        exp_pkt.set_do_not_care_scapy(packet.IP, 'chksum')

    testutils.send(ptfadapter, 5, pkt)
    testutils.verify_packet_any_port(ptfadapter, exp_pkt, ports=expected_ports)
Beispiel #13
0
    def verify_traffic(duthost,
                       connection,
                       route,
                       is_duthost_active=True,
                       is_route_existed=True):
        prefix = ipaddress.ip_network(route["prefix"])
        dst_host = str(next(prefix.hosts()))
        pkt, exp_pkt = build_packet_to_server(duthost, ptfadapter, dst_host)
        ptf_t1_intf = random.choice(get_t1_ptf_ports(duthost, tbinfo))
        ptf_t1_intf_index = int(ptf_t1_intf.strip("eth"))
        is_tunnel_traffic_existed = is_route_existed and not is_duthost_active
        is_server_traffic_existed = is_route_existed and is_duthost_active

        if isinstance(prefix, ipaddress.IPv4Network):
            tunnel_innner_pkt = pkt[scapyall.IP].copy()
            tunnel_innner_pkt[scapyall.IP].ttl -= 1
        else:
            tunnel_innner_pkt = pkt[scapyall.IPv6].copy()
            tunnel_innner_pkt[scapyall.IPv6].hlim -= 1
        tunnel_monitor = tunnel_traffic_monitor(
            duthost,
            existing=is_tunnel_traffic_existed,
            inner_packet=tunnel_innner_pkt)
        server_traffic_monitor = ServerTrafficMonitor(
            duthost,
            ptfhost,
            vmhost,
            tbinfo,
            connection["test_intf"],
            conn_graph_facts,
            exp_pkt,
            existing=is_server_traffic_existed)
        with tunnel_monitor, server_traffic_monitor:
            testutils.send(ptfadapter, ptf_t1_intf_index, pkt, count=10)
Beispiel #14
0
    def test_drop_ip_packet_with_wrong_0xffff_chksum(self, duthost, ptfadapter, common_param):
        # GIVEN a random normal ip packet, and manually modify checksum to 0xffff
        # WHEN send the packet to DUT
        # THEN DUT should drop it and add drop count
        (peer_ip_ifaces_pair, ptf_port_idx, pc_ports_map, ptf_indices) = common_param
        pkt = testutils.simple_ip_packet(
            eth_dst=duthost.facts["router_mac"],
            eth_src=ptfadapter.dataplane.get_mac(0, ptf_port_idx),
            ip_src=peer_ip_ifaces_pair[0][0],
            ip_dst=peer_ip_ifaces_pair[1][0])

        pkt.payload.chksum = 0xffff

        out_ifaces = TestIPPacket.parse_interfaces(
            duthost.command("show ip route %s" % peer_ip_ifaces_pair[1][0])["stdout_lines"],
            pc_ports_map)

        duthost.command("portstat -c")
        ptfadapter.dataplane.flush()
        testutils.send(ptfadapter, ptf_port_idx, pkt, self.PKT_NUM)
        time.sleep(5)

        portstat_out = parse_portstat(duthost.command("portstat")["stdout_lines"])

        rx_ok = int(portstat_out[peer_ip_ifaces_pair[0][1][0]]["rx_ok"].replace(",", ""))
        rx_drp = int(portstat_out[peer_ip_ifaces_pair[0][1][0]]["rx_drp"].replace(",", ""))
        tx_ok = TestIPPacket.sum_portstat_ifaces_counts(portstat_out, out_ifaces, "tx_ok")
        tx_drp = TestIPPacket.sum_portstat_ifaces_counts(portstat_out, out_ifaces, "tx_drp")

        pytest_assert(self.PKT_NUM_MIN <= rx_ok <= self.PKT_NUM_MAX, "rx_ok unexpected")
        pytest_assert(self.PKT_NUM_MIN <= rx_drp <= self.PKT_NUM_MAX, "rx_drp unexpected")
        pytest_assert(tx_ok <= self.PKT_NUM_ZERO, "tx_ok unexpected")
        pytest_assert(tx_drp <= self.PKT_NUM_ZERO, "tx_drp unexpected")
Beispiel #15
0
def test_decap_active_tor(apply_active_state_to_orchagent,
                          build_encapsulated_packet, rand_selected_interface,
                          ptfadapter, tbinfo, rand_selected_dut,
                          tunnel_traffic_monitor):
    tor = rand_selected_dut
    encapsulated_packet = build_encapsulated_packet
    iface, _ = rand_selected_interface

    exp_ptf_port_index = get_ptf_server_intf_index(tor, tbinfo, iface)
    exp_pkt = build_expected_packet_to_server(encapsulated_packet)

    ptfadapter.dataplane.flush()
    ptf_t1_intf = random.choice(get_t1_ptf_ports(tor, tbinfo))
    logging.info("send encapsulated packet from ptf t1 interface %s",
                 ptf_t1_intf)
    testutils.send(ptfadapter,
                   int(ptf_t1_intf.strip("eth")),
                   encapsulated_packet,
                   count=10)
    _, rec_pkt = testutils.verify_packet_any_port(ptfadapter,
                                                  exp_pkt,
                                                  ports=[exp_ptf_port_index])
    rec_pkt = Ether(rec_pkt)
    logging.info("received decap packet:\n%s",
                 tunnel_traffic_monitor._dump_show_str(rec_pkt))
    exp_ttl = encapsulated_packet[IP].payload[IP].ttl - 1
    exp_tos = encapsulated_packet[IP].payload[IP].tos
    if rec_pkt[IP].ttl != exp_ttl:
        pytest.fail("the expected ttl should be %s" % exp_ttl)
    if rec_pkt[IP].tos != exp_tos:
        pytest.fail("the expected tos should be %s" % exp_tos)
Beispiel #16
0
def send_recv_ping_packet(ptfadapter, ptf_send_port, ptf_recv_ports, dst_mac,
                          src_ip, dst_ip):
    pkt = testutils.simple_icmp_packet(eth_dst=dst_mac,
                                       ip_src=src_ip,
                                       ip_dst=dst_ip,
                                       icmp_type=8,
                                       icmp_data="")

    ext_pkt = pkt.copy()
    ext_pkt['Ether'].src = dst_mac

    masked_exp_pkt = Mask(ext_pkt)
    masked_exp_pkt.set_do_not_care_scapy(scapy.Ether, "dst")
    masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "tos")
    masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "len")
    masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "id")
    masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "flags")
    masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "frag")
    masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "ttl")
    masked_exp_pkt.set_do_not_care_scapy(scapy.IP, "chksum")

    masked_exp_pkt.set_do_not_care_scapy(scapy.ICMP, "code")
    masked_exp_pkt.set_do_not_care_scapy(scapy.ICMP, "chksum")
    masked_exp_pkt.set_do_not_care_scapy(scapy.ICMP, "id")
    masked_exp_pkt.set_do_not_care_scapy(scapy.ICMP, "seq")

    logger.info(
        'send ping request packet send port {}, recv port {}, dmac: {}, dip: {}'
        .format(ptf_send_port, ptf_recv_ports, dst_mac, dst_ip))
    testutils.send(ptfadapter, ptf_send_port, pkt)
    testutils.verify_packet_any_port(ptfadapter,
                                     masked_exp_pkt,
                                     ptf_recv_ports,
                                     timeout=WAIT_EXPECTED_PACKET_TIMEOUT)
    def testDhcpPacketForwarding(self, duthost, testPorts, ptfadapter,
                                 pktInfo):
        """
        Validates that DHCP Discover/Offer/Request/Ack (DORA) packets are forwarded through T1 devices

         Args:
            duthost(Ansible Fixture): instance of SonicHost class of DUT
            testPorts(Ansible Fixture, dict): contains downstream/upstream test ports information
            ptfadapter(Ansible Fixture): instance of PTF Adapter
            pktInfo(Pytest Params<dict>): test parameters containing information on which ports used for
                                          sending/receiving DHCP packet and
                                          DHCP packet to send
        """
        ptfadapter.dataplane.flush()

        dhcpPacket = pktInfo["pktGen"](duthost.facts["router_mac"])
        testutils.send(ptfadapter, random.choice(testPorts[pktInfo["txDir"]]),
                       dhcpPacket)

        # Update fields of the forwarded packet
        dhcpPacket[scapy.Ether].src = duthost.facts["router_mac"]
        dhcpPacket[
            scapy.IP].ttl = dhcpPacket[scapy.IP].ttl - duthost.ttl_decr_value

        expectedDhcpPacket = Mask(dhcpPacket)
        expectedDhcpPacket.set_do_not_care_scapy(scapy.Ether, "dst")
        expectedDhcpPacket.set_do_not_care_scapy(scapy.IP, "chksum")

        _, receivedPacket = testutils.verify_packet_any_port(
            ptfadapter, expectedDhcpPacket, ports=testPorts[pktInfo["rxDir"]])
        logger.info("Received packet: %s",
                    scapy.Ether(receivedPacket).summary())
Beispiel #18
0
def test_decap_standby_tor(apply_mock_dual_tor_tables,
                           apply_mock_dual_tor_kernel_configs,
                           apply_standby_state_to_orchagent,
                           build_encapsulated_packet, rand_selected_interface,
                           ptfadapter, tbinfo, rand_selected_dut,
                           tunnel_traffic_monitor):
    tor = rand_selected_dut
    encapsulated_packet = build_encapsulated_packet
    iface, _ = rand_selected_interface

    exp_ptf_port_index = get_ptf_server_intf_index(tor, tbinfo, iface)
    exp_pkt = build_expected_packet_to_server(encapsulated_packet)

    ptf_t1_intf = random.choice(get_t1_ptf_ports(tor, tbinfo))
    logging.info("send encapsulated packet from ptf t1 interface %s",
                 ptf_t1_intf)
    with tunnel_traffic_monitor(tor, existing=False):
        testutils.send(ptfadapter,
                       int(ptf_t1_intf.strip("eth")),
                       encapsulated_packet,
                       count=1)

    testutils.verify_no_packet_any(ptfadapter,
                                   exp_pkt,
                                   ports=[exp_ptf_port_index])
Beispiel #19
0
def run_test_ipv4(ptfadapter, facts):
    logger.info("Running test with ipv4 packets")
    pkt = testutils.simple_udp_packet(eth_dst=facts['src_router_mac'],
                                      eth_src=facts['src_host_mac'],
                                      ip_src=facts['dst_host_ipv4'],
                                      ip_dst=facts['dst_host_ipv4'],
                                      ip_ttl=DEFAULT_HLIM_TTL)
    logger.info("\nSend Packet:\neth_dst: {}, eth_src: {}, ipv4 ip: {}".format(
        facts['src_router_mac'], facts['src_host_mac'],
        facts['dst_host_ipv4']))

    testutils.send(ptfadapter, facts['src_port_ids'][0], pkt)

    exp_pkt = testutils.simple_udp_packet(eth_dst=facts['dst_host_mac'],
                                          eth_src=facts['dst_router_mac'],
                                          ip_src=facts['dst_host_ipv4'],
                                          ip_dst=facts['dst_host_ipv4'],
                                          ip_ttl=DEFAULT_HLIM_TTL - 1)
    logger.info(
        "\nExpect Packet:\neth_dst: {}, eth_src: {}, ipv4 ip: {}".format(
            facts['dst_host_mac'], facts['dst_router_mac'],
            facts['dst_host_ipv4']))

    testutils.verify_packet_any_port(ptfadapter,
                                     exp_pkt,
                                     facts['dst_port_ids'],
                                     timeout=WAIT_EXPECTED_PACKET_TIMEOUT)
Beispiel #20
0
def send_arp_request(ptfadapter, source_port, source_mac, dest_mac, vlan_id):
    """
    send arp request packet
    :param ptfadapter: PTF adapter object
    :param source_port: source port
    :param source_mac: source MAC
    :param dest_mac: destination MAC
    :param vlan_id: VLAN id
    :return:
    """
    pkt = testutils.simple_arp_packet(
        pktlen=60,
        eth_dst=dest_mac,
        eth_src=source_mac,
        vlan_vid=vlan_id,
        vlan_pcp=0,
        arp_op=1,
        ip_snd='10.10.1.3',
        ip_tgt='10.10.1.2',
        hw_snd=source_mac,
        hw_tgt='ff:ff:ff:ff:ff:ff',
    )
    logger.debug(
        'send ARP request packet source port id {} smac: {} dmac: {} vlan: {}'.
        format(source_port, source_mac, dest_mac, vlan_id))
    testutils.send(ptfadapter, source_port, pkt)
Beispiel #21
0
def test_ecn_during_decap_on_active(
    apply_active_state_to_orchagent,
    build_encapsulated_ip_packet,
    rand_selected_interface, 
    ptfadapter,
    tbinfo, 
    rand_selected_dut, 
    tunnel_traffic_monitor
):
    """
    Test if the ECN stamping on inner header is matching with outer during decap on active
    """
    tor = rand_selected_dut
    encapsulated_packet = build_encapsulated_ip_packet
    iface, _ = rand_selected_interface

    exp_ptf_port_index = get_ptf_server_intf_index(tor, tbinfo, iface)
    exp_pkt = build_expected_packet_to_server(encapsulated_packet)

    ptfadapter.dataplane.flush()
    ptf_t1_intf = random.choice(get_t1_ptf_ports(tor, tbinfo))
    logging.info("send encapsulated packet from ptf t1 interface %s", ptf_t1_intf)
    testutils.send(ptfadapter, int(ptf_t1_intf.strip("eth")), encapsulated_packet, count=10)
    time.sleep(10)

    exp_tos = encapsulated_packet[IP].payload[IP].tos
    exp_ecn = exp_tos & 3
    verify_ecn_on_received_packet(ptfadapter, exp_pkt, exp_ptf_port_index, exp_ecn)
Beispiel #22
0
def test_dscp_to_queue_during_encap_on_standby(
    build_non_encapsulated_ip_packet,
    rand_selected_interface, ptfadapter,
    tbinfo, 
    rand_selected_dut, 
    tunnel_traffic_monitor, 
    duthosts, 
    rand_one_dut_hostname
):
    """
    Test if DSCP to Q mapping for outer header is matching with inner header during encap on standby
    """
    rand_selected_dut.shell("/usr/local/bin/write_standby.py")

    tor = rand_selected_dut
    non_encapsulated_packet = build_non_encapsulated_ip_packet
    iface, _ = rand_selected_interface

    exp_ptf_port_index = get_ptf_server_intf_index(tor, tbinfo, iface)

    # Clear queue counters
    duthost = duthosts[rand_one_dut_hostname]
    duthost.shell('sonic-clear queuecounters')
    logging.info("Clearing queue counters before starting traffic")

    ptfadapter.dataplane.flush()
    ptf_t1_intf = random.choice(get_t1_ptf_ports(tor, tbinfo))
    logging.info("send IP packet from ptf t1 interface %s", ptf_t1_intf)
    with tunnel_traffic_monitor(tor, existing=True):
       testutils.send(ptfadapter, int(ptf_t1_intf.strip("eth")), non_encapsulated_packet, count=10)
Beispiel #23
0
def test_vlan_tc3_send_invalid_vid(ptfadapter, vlan_ports_list):
    """
    Test case #3
    Send packets with invalid VLAN ID
    Verify no port can receive these pacekts
    """

    logger.info("Test case #3 starting ...")

    invalid_tagged_pkt = build_icmp_packet(4095)
    masked_invalid_tagged_pkt = Mask(invalid_tagged_pkt)
    masked_invalid_tagged_pkt.set_do_not_care_scapy(scapy.Dot1Q, "vlan")

    for vlan_port in vlan_ports_list:
        src_port = vlan_port["port_index"]
        dst_ports = [
            port["port_index"] for port in vlan_ports_list if port != vlan_port
        ]
        logger.info("Send invalid tagged packet " + " from " + str(src_port) +
                    "...")
        logger.info(
            invalid_tagged_pkt.sprintf(
                "%Ether.src% %IP.src% -> %Ether.dst% %IP.dst%"))
        testutils.send(ptfadapter, src_port, invalid_tagged_pkt)
        logger.info("Check on " + str(dst_ports) + "...")
        testutils.verify_no_packet_any(ptfadapter, masked_invalid_tagged_pkt,
                                       dst_ports)
Beispiel #24
0
def test_vlan_tc1_send_untagged(
        ptfadapter, work_vlan_ports_list,
        toggle_all_simulator_ports_to_rand_selected_tor_m):
    """
    Test case #1
    Verify packets egress without tag from ports whose PVID same with ingress port
    Verify packets egress with tag from ports who include VLAN ID but PVID different from ingress port.
    """

    logger.info("Test case #1 starting ...")

    for vlan_port in work_vlan_ports_list:
        pkt = build_icmp_packet(0)
        logger.info("Send untagged packet from {} ...".format(
            vlan_port["port_index"][0]))
        logger.info(
            pkt.sprintf("%Ether.src% %IP.src% -> %Ether.dst% %IP.dst%"))
        if vlan_port['pvid'] != 0:
            testutils.send(ptfadapter, vlan_port["port_index"][0], pkt)
            verify_icmp_packets(ptfadapter, work_vlan_ports_list, vlan_port,
                                vlan_port["pvid"])
        else:
            exp_pkt = Mask(pkt)
            exp_pkt.set_do_not_care_scapy(scapy.Dot1Q, "vlan")
            dst_ports = []
            for port in work_vlan_ports_list:
                dst_ports += port["port_index"] if port != vlan_port else []
            testutils.send(ptfadapter, vlan_port["port_index"][0], pkt)
            logger.info("Check on " + str(dst_ports) + "...")
            testutils.verify_no_packet_any(ptfadapter, exp_pkt, dst_ports)
Beispiel #25
0
def test_tagged_arp_pkt(ptfadapter, vlan_ports_list, duthosts, rand_one_dut_hostname, toggle_all_simulator_ports_to_rand_selected_tor):
    """
    Send tagged GARP packets from each port.
    Verify packets egress without tag from ports whose PVID same with ingress port.
    Verify packets egress with tag from ports who include VLAN ID but PVID different from ingress port.
    verify show arp command on DUT.
    """
    duthost = duthosts[rand_one_dut_hostname]
    for vlan_port in vlan_ports_list:
        port_index = vlan_port["port_index"][0]
        # Send GARP packets to switch to populate the arp table with dummy MACs for each port
        # Totally 10 dummy MACs for each port, send 1 packet for each dummy MAC
        # ARP table will be cleaned up before each iteration, so there won't be any conflict MAC and IP
        dummy_macs = ['{}:{:02x}:{:02x}'.format(DUMMY_MAC_PREFIX, port_index&0xFF, i+1)
                      for i in range(DUMMY_ARP_COUNT)]
        dummy_ips = ['{}.{:d}.{:d}'.format(DUMMY_IP_PREFIX, port_index&0xFF, i+1)
                      for i in range(DUMMY_ARP_COUNT)]
        for permit_vlanid in map(int, vlan_port["permit_vlanid"]):
            logger.info('Test ARP: interface %s, VLAN %u' % (vlan_port["dev"], permit_vlanid))
            # Perform ARP clean up
            arp_cleanup(duthost)
            for i in range(DUMMY_ARP_COUNT):
                pkt = build_arp_packet(permit_vlanid, dummy_macs[i], dummy_ips[i])
                exp_untagged_pkt = build_arp_packet(0, dummy_macs[i], dummy_ips[i])
                # vlan priority attached to packets is determined by the port, so we ignore it here
                exp_tagged_pkt = Mask(pkt)
                exp_tagged_pkt.set_do_not_care_scapy(scapy.Dot1Q, "prio")
                logger.info("Send tagged({}) packet from {} ...".format(permit_vlanid, port_index))
                testutils.send(ptfadapter, port_index, pkt)
                verify_arp_packets(ptfadapter, vlan_ports_list, vlan_port, permit_vlanid, exp_untagged_pkt, exp_tagged_pkt)

            res = duthost.command('show arp')
            assert res['rc'] == 0
            logger.info('"show arp" output on DUT:\n{}'.format(pprint.pformat(res['stdout_lines'])))

            arp_cnt = 0
            for l in res['stdout_lines']:
                # Address MacAddress Iface Vlan
                items = l.split()
                if len(items) != 4:
                    continue
                # Vlan must be number
                if not items[3].isdigit():
                    continue
                arp_cnt += 1
                ip = items[0]
                mac = items[1]
                ifname = items[2]
                vlan_id = int(items[3])
                assert ip in dummy_ips
                assert mac in dummy_macs
                # 'show arp' command gets iface from FDB table,
                # if 'show arp' command was earlier than FDB table update, ifname would be '-'
                if ifname == '-':
                    logger.info('Ignore unknown iface...')
                else:
                    assert ifname == vlan_port["dev"]
                assert vlan_id == permit_vlanid
            assert arp_cnt == DUMMY_ARP_COUNT
Beispiel #26
0
def send_recv_eth(duthost, ptfadapter, source_ports, source_mac, dest_ports,
                  dest_mac, src_vlan, dst_vlan):
    """
    send ethernet packet and verify it on dest_port
    :param ptfadapter: PTF adapter object
    :param source_port: source port
    :param source_mac: source MAC
    :param dest_port: destination port to receive packet on
    :param dest_mac: destination MAC
    :param vlan_id: VLAN id
    :return:
    """
    pkt = simple_eth_packet(eth_dst=dest_mac,
                            eth_src=source_mac,
                            vlan_vid=src_vlan)
    exp_pkt = simple_eth_packet(eth_dst=dest_mac,
                                eth_src=source_mac,
                                vlan_vid=dst_vlan)
    if dst_vlan:
        # expect to receive tagged packet:
        # sonic device might modify the 802.1p field,
        # need to use Mask to ignore the priority field.
        exp_pkt = Mask(exp_pkt)
        exp_pkt.set_do_not_care_scapy(scapy.Dot1Q, "prio")
    logger.debug(
        'send packet src port {} smac: {} dmac: {} vlan: {} verifying on dst port {}'
        .format(source_ports, source_mac, dest_mac, src_vlan, dest_ports))

    # fdb test will send lots of pkts between paired ports, it's hard to guarantee there is no congestion
    # on server side during this period. So tolerant to retry 3 times before complain the assert.

    retry_count = 3
    for _ in range(retry_count):
        try:
            ptfadapter.dataplane.flush()
            testutils.send(ptfadapter, source_ports[0], pkt)
            if len(dest_ports) == 1:
                testutils.verify_packet(
                    ptfadapter,
                    exp_pkt,
                    dest_ports[0],
                    timeout=FDB_WAIT_EXPECTED_PACKET_TIMEOUT)
            else:
                testutils.verify_packet_any_port(
                    ptfadapter,
                    exp_pkt,
                    dest_ports,
                    timeout=FDB_WAIT_EXPECTED_PACKET_TIMEOUT)
            break
        except:
            pass
    else:
        result = duthost.command("show mac", module_ignore_errors=True)
        logger.debug("Show mac results {}".format(result['stdout']))
        pytest_assert(
            False, "Expected packet was not received on ports {}"
            "Dest MAC in fdb is {}".format(
                dest_ports,
                dest_mac.lower() in result['stdout'].lower()))
Beispiel #27
0
def test_snmp_fdb_send_tagged(
        ptfadapter, utils_vlan_ports_list,
        toggle_all_simulator_ports_to_rand_selected_tor_m, duthost, localhost,
        creds_all_duts):
    """
    Send tagged packets from each port.
    Verify SNMP FDB entry
    """
    cfg_facts = duthost.config_facts(host=duthost.hostname,
                                     source="persistent")['ansible_facts']
    config_portchannels = cfg_facts.get('PORTCHANNEL', {})
    send_cnt = 0
    send_portchannels_cnt = 0
    for vlan_port in utils_vlan_ports_list:
        port_index = vlan_port["port_index"][0]
        for permit_vlanid in map(int, vlan_port["permit_vlanid"]):
            dummy_mac = '{}:{:02x}:{:02x}'.format(DUMMY_MAC_PREFIX,
                                                  (port_index >> 8) & 0xFF,
                                                  port_index & 0xFF)
            pkt = build_icmp_packet(permit_vlanid, dummy_mac)
            logger.info("Send tagged({}) packet from {} ...".format(
                permit_vlanid, port_index))
            logger.info(
                pkt.sprintf("%Ether.src% %IP.src% -> %Ether.dst% %IP.dst%"))
            testutils.send(ptfadapter, port_index, pkt)
            send_cnt += 1
            if vlan_port['dev'] in config_portchannels:
                send_portchannels_cnt += 1
    # Flush dataplane
    ptfadapter.dataplane.flush()

    hostip = duthost.host.options['inventory_manager'].get_host(
        duthost.hostname).vars['ansible_host']
    snmp_facts = get_snmp_facts(
        localhost,
        host=hostip,
        version="v2c",
        community=creds_all_duts[duthost]["snmp_rocommunity"],
        wait=True)['ansible_facts']
    assert 'snmp_fdb' in snmp_facts
    assert 'snmp_interfaces' in snmp_facts
    dummy_mac_cnt = 0
    recv_portchannels_cnt = 0
    for key in snmp_facts['snmp_fdb']:
        # key is string: vlan.mac
        items = key.split('.')
        if len(items) != 2:
            continue
        logger.info("FDB entry: {}".format(items))
        if DUMMY_MAC_PREFIX in items[1]:
            dummy_mac_cnt += 1
            idx = str(snmp_facts['snmp_fdb'][key])
            assert idx in snmp_facts['snmp_interfaces']
            assert 'name' in snmp_facts['snmp_interfaces'][idx]
            if snmp_facts['snmp_interfaces'][idx][
                    'name'] in config_portchannels:
                recv_portchannels_cnt += 1
    assert send_cnt == dummy_mac_cnt, "Dummy MAC count does not match"
    assert send_portchannels_cnt == recv_portchannels_cnt, "Portchannels count does not match"
Beispiel #28
0
def send_packets(pkt, duthost, ptfadapter, ptf_tx_port_id, num_packets=1):
    # Clear packets buffer on PTF
    ptfadapter.dataplane.flush()
    time.sleep(1)

    # Send packets
    testutils.send(ptfadapter, ptf_tx_port_id, pkt, count=num_packets)
    time.sleep(1)
Beispiel #29
0
    def test_unmatched_blocked(self, setup, direction, ptfadapter):
        """ verify that unmatched packet is dropped """

        pkt = self.tcp_packet(setup, direction, ptfadapter)
        exp_pkt = self.expected_mask_routed_packet(pkt)

        testutils.send(ptfadapter, self.get_src_port(setup, direction), pkt)
        testutils.verify_no_packet_any(ptfadapter, exp_pkt, ports=self.get_dst_ports(setup, direction))
Beispiel #30
0
def verify_unicast_packets(ptfadapter, send_pkt, exp_pkt, src_port, dst_ports):
    testutils.send(ptfadapter, src_port, send_pkt)
    try:
        testutils.verify_packets_any(ptfadapter, exp_pkt, ports=dst_ports)
    except AssertionError as detail:
        if "Did not receive expected packet on any of ports" in str(detail):
            logger.error("Expected packet was not received")
        raise