summaryrefslogtreecommitdiffstats
path: root/test/test_l2bd.py
blob: 46ba2e49c13a5cd258ba9552b297e9654c606087 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python

import unittest
import random

from scapy.packet import Raw
from scapy.layers.l2 import Ether, Dot1Q
from scapy.layers.inet import IP, UDP

from framework import VppTestCase, VppTestRunner
from util import Host
from vpp_sub_interface import VppDot1QSubint, VppDot1ADSubint


class TestL2bd(VppTestCase):
    """ L2BD Test Case """

    @classmethod
    def setUpClass(cls):
        """
        Perform standard class setup (defined by class method setUpClass in
        class VppTestCase) before running the test case, set test case related
        variables and configure VPP.

        :var int bd_id: Bridge domain ID.
        :var int mac_entries_count: Number of MAC entries for bridge-domain to
            learn.
        :var int dot1q_tag: VLAN tag for dot1q sub-interface.
        :var int dot1ad_sub_id: SubID of dot1ad sub-interface.
        :var int dot1ad_outer_tag: VLAN S-tag for dot1ad sub-interface.
        :var int dot1ad_inner_tag: VLAN C-tag for dot1ad sub-interface.
        :var int sl_pkts_per_burst: Number of packets in burst for single-loop
            test.
        :var int dl_pkts_per_burst: Number of packets in burst for dual-loop
            test.
        """
        super(TestL2bd, cls).setUpClass()

        # Test variables
        cls.bd_id = 1
        cls.mac_entries_count = 100
        # cls.dot1q_sub_id = 100
        cls.dot1q_tag = 100
        cls.dot1ad_sub_id = 20
        cls.dot1ad_outer_tag = 200
        cls.dot1ad_inner_tag = 300
        cls.sl_pkts_per_burst = 2
        cls.dl_pkts_per_burst = 257

        try:
            # create 3 pg interfaces
            cls.create_pg_interfaces(range(3))

            # create 2 sub-interfaces for pg1 and pg2
            cls.sub_interfaces = [
                VppDot1QSubint(cls, cls.pg1, cls.dot1q_tag),
                VppDot1ADSubint(cls, cls.pg2, cls.dot1ad_sub_id,
                                cls.dot1ad_outer_tag, cls.dot1ad_inner_tag)]

            # packet flows mapping pg0 -> pg1, pg2, etc.
            cls.flows = dict()
            cls.flows[cls.pg0] = [cls.pg1, cls.pg2]
            cls.flows[cls.pg1] = [cls.pg0, cls.pg2]
            cls.flows[cls.pg2] = [cls.pg0, cls.pg1]

            # packet sizes
            cls.pg_if_packet_sizes = [64, 512, 1518, 9018]
            cls.sub_if_packet_sizes = [64, 512, 1518 + 4, 9018 + 4]

            cls.interfaces = list(cls.pg_interfaces)
            cls.interfaces.extend(cls.sub_interfaces)

            # Create BD with MAC learning enabled and put interfaces and
            #  sub-interfaces to this BD
            for pg_if in cls.pg_interfaces:
                sw_if_index = pg_if.sub_if.sw_if_index \
                    if hasattr(pg_if, 'sub_if') else pg_if.sw_if_index
                cls.vapi.sw_interface_set_l2_bridge(sw_if_index,
                                                    bd_id=cls.bd_id)

            # setup all interfaces
            for i in cls.interfaces:
                i.admin_up()

            # mapping between packet-generator index and lists of test hosts
            cls.hosts_by_pg_idx = dict()

            # create test host entries and inject packets to learn MAC entries
            # in the bridge-domain
            cls.create_hosts_and_learn(cls.mac_entries_count)
            cls.logger.info(cls.vapi.ppcli("show l2fib"))

        except Exception:
            super(TestL2bd, cls).tearDownClass()
            raise

    def setUp(self):
        """
        Clear trace and packet infos before running each test.
        """
        super(TestL2bd, self).setUp()
        self.packet_infos = {}

    def tearDown(self):
        """
        Show various debug prints after each test.
        """
        super(TestL2bd, self).tearDown()
        if not self.vpp_dead:
            self.logger.info(self.vapi.ppcli("show l2fib verbose"))
            self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" %
                                           self.bd_id))

    @classmethod
    def create_hosts_and_learn(cls, count):
        """
        Create required number of host MAC addresses and distribute them among
        interfaces. Create host IPv4 address for every host MAC address. Create
        L2 MAC packet stream with host MAC addresses per interface to let
        the bridge domain learn these MAC addresses.

        :param count: Integer number of hosts to create MAC/IPv4 addresses for.
        """
        n_int = len(cls.pg_interfaces)
        macs_per_if = count / n_int
        i = -1
        for pg_if in cls.pg_interfaces:
            i += 1
            start_nr = macs_per_if * i
            end_nr = count if i == (n_int - 1) else macs_per_if * (i + 1)
            cls.hosts_by_pg_idx[pg_if.sw_if_index] = []
            hosts = cls.hosts_by_pg_idx[pg_if.sw_if_index]
            packets = []
            for j in range(start_nr, end_nr):
                host = Host(
                    "00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j),
                    "172.17.1%02x.%u" % (pg_if.sw_if_index, j))
                packet = (Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac))
                hosts.append(host)
                if hasattr(pg_if, 'sub_if'):
                    packet = pg_if.sub_if.add_dot1_layer(packet)
                packets.append(packet)
            pg_if.add_stream(packets)
        cls.logger.info("Sending broadcast eth frames for MAC learning")
        cls.pg_start()

    def create_stream(self, src_if, packet_sizes, packets_per_burst):
        """
        Create input packet stream for defined interface.

        :param object src_if: Interface to create packet stream for.
        :param list packet_sizes: List of required packet sizes.
        :param int packets_per_burst: Number of packets in burst.
        :return: Stream of packets.
        """
        pkts = []
        for i in range(0, packets_per_burst):
            dst_if = self.flows[src_if][i % 2]
            dst_host = random.choice(self.hosts_by_pg_idx[dst_if.sw_if_index])
            src_host = random.choice(self.hosts_by_pg_idx[src_if.sw_if_index])
            pkt_info = self.create_packet_info(
                src_if.sw_if_index, dst_if.sw_if_index)
            payload = self.info_to_payload(pkt_info)
            p = (Ether(dst=dst_host.mac, src=src_host.mac) /
                 IP(src=src_host.ip4, dst=dst_host.ip4) /
                 UDP(sport=1234, dport=1234) /
                 Raw(payload))
            pkt_info.data = p.copy()
            if hasattr(src_if, 'sub_if'):
                p = src_if.sub_if.add_dot1_layer(p)
            size = random.choice(packet_sizes)
            self.extend_packet(p, size)
            pkts.append(p)
        return pkts

    def verify_capture(self, pg_if, capture):
        """
        Verify captured input packet stream for defined interface.

        :param object pg_if: Interface to verify captured packet stream for.
        :param list capture: Captured packet stream.
        """
        last_info = dict()
        for i in self.pg_interfaces:
            last_info[i.sw_if_index] = None
        dst_sw_if_index = pg_if.sw_if_index
        for packet in capture:
            payload_info = self.payload_to_info(str(packet[Raw]))
            src_sw_if_index = payload_info.src
            src_if = None
            for ifc in self.pg_interfaces:
                if ifc != pg_if:
                    if ifc.sw_if_index == src_sw_if_index:
                        src_if = ifc
                        break
            if hasattr(src_if, 'sub_if'):
                # Check VLAN tags and Ethernet header
                packet = src_if.sub_if.remove_dot1_layer(packet)
            self.assertTrue(Dot1Q not in packet)
            try:
                ip = packet[IP]
                udp = packet[UDP]
                packet_index = payload_info.index
                self.assertEqual(payload_info.dst, dst_sw_if_index)
                self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
                                  (pg_if.name, payload_info.src, packet_index))
                next_info = self.get_next_packet_info_for_interface2(
                    payload_info.src, dst_sw_if_index,
                    last_info[payload_info.src])
                last_info[payload_info.src] = next_info
                self.assertTrue(next_info is not None)
                self.assertEqual(packet_index, next_info.index)
                saved_packet = next_info.data
                # Check standard fields
                self.assertEqual(ip.src, saved_packet[IP].src)
                self.assertEqual(ip.dst, saved_packet[IP].dst)
                self.assertEqual(udp.sport, saved_packet[UDP].sport)
                self.assertEqual(udp.dport, saved_packet[UDP].dport)
            except:
                self.logger.error("Unexpected or invalid packet:")
                self.logger.error(packet.show())
                raise
        for i in self.pg_interfaces:
            remaining_packet = self.get_next_packet_info_for_interface2(
                i, dst_sw_if_index, last_info[i.sw_if_index])
            self.assertTrue(
                remaining_packet is None,
                "Port %u: Packet expected from source %u didn't arrive" %
                (dst_sw_if_index, i.sw_if_index))

    def run_l2bd_test(self, pkts_per_burst):
        """ L2BD MAC learning test """

        # Create incoming packet streams for packet-generator interfaces
        for i in self.pg_interfaces:
            packet_sizes = self.sub_if_packet_sizes if hasattr(i, 'sub_if') \
                else self.pg_if_packet_sizes
            pkts = self.create_stream(i, packet_sizes, pkts_per_burst)
            i.add_stream(pkts)

        # Enable packet capture and start packet sending
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Verify outgoing packet streams per packet-generator interface
        for i in self.pg_interfaces:
            capture = i.get_capture()
            self.logger.info("Verifying capture on interface %s" % i.name)
            self.verify_capture(i, capture)

    def test_l2bd_sl(self):
        """ L2BD MAC learning single-loop test

        Test scenario:
            1.config
                MAC learning enabled
                learn 100 MAC enries
                3 interfaces: untagged, dot1q, dot1ad (dot1q used instead of
                dot1ad in the first version)

            2.sending l2 eth pkts between 3 interface
                64B, 512B, 1518B, 9200B (ether_size)
                burst of 2 pkts per interface
        """

        self.run_l2bd_test(self.sl_pkts_per_burst)

    def test_l2bd_dl(self):
        """ L2BD MAC learning dual-loop test

         Test scenario:
            1.config
                MAC learning enabled
                learn 100 MAC enries
                3 interfaces: untagged, dot1q, dot1ad (dot1q used instead of
                dot1ad in the first version)

            2.sending l2 eth pkts between 3 interface
                64B, 512B, 1518B, 9200B (ether_size)
                burst of 257 pkts per interface
        """

        self.run_l2bd_test(self.dl_pkts_per_burst)


if __name__ == '__main__':
    unittest.main(testRunner=VppTestRunner)
ss="k">sizeof (u32), .format_trace = format_icmp_echo_trace, .n_next_nodes = ICMP4_ECHO_REPLY_N_NEXT, .next_nodes = { [ICMP4_ECHO_REPLY_NEXT_DROP] = "error-drop", [ICMP4_ECHO_REPLY_NEXT_PUNT] = "error-punt", }, }; /* *INDENT-ON* */ char *ip6_lookup_next_nodes[] = IP6_LOOKUP_NEXT_NODES; char *ip4_lookup_next_nodes[] = IP4_LOOKUP_NEXT_NODES; /* get first interface address */ static ip6_address_t * ip6_interface_first_address (ip6_main_t * im, u32 sw_if_index) { ip_lookup_main_t *lm = &im->lookup_main; ip_interface_address_t *ia = 0; ip6_address_t *result = 0; /* *INDENT-OFF* */ foreach_ip_interface_address (lm, ia, sw_if_index, 1 /* honor unnumbered */ , ({ ip6_address_t * a = ip_interface_address_get_address (lm, ia); result = a; break; })); /* *INDENT-ON* */ return result; } /* Fill in the ICMP ECHO structure, return the safety-checked and possibly shrunk data_len */ static u16 init_icmp46_echo_request (icmp46_echo_request_t * icmp46_echo, u16 seq_host, u16 id_host, u16 data_len) { int i; icmp46_echo->seq = clib_host_to_net_u16 (seq_host); icmp46_echo->id = clib_host_to_net_u16 (id_host); for (i = 0; i < sizeof (icmp46_echo->data); i++) { icmp46_echo->data[i] = i % 256; } if (data_len > sizeof (icmp46_echo_request_t)) { data_len = sizeof (icmp46_echo_request_t); } return data_len; } static send_ip46_ping_result_t send_ip6_ping (vlib_main_t * vm, ip6_main_t * im, u32 table_id, ip6_address_t * pa6, u32 sw_if_index, u16 seq_host, u16 id_host, u16 data_len, u8 verbose) { icmp6_echo_request_header_t *h0; u32 bi0 = 0; int bogus_length = 0; vlib_buffer_t *p0; vlib_frame_t *f; u32 *to_next; if (vlib_buffer_alloc (vm, &bi0, 1) != 1) return SEND_PING_ALLOC_FAIL; p0 = vlib_get_buffer (vm, bi0); /* * if the user did not provide a source interface, use the any interface * that the destination resolves via. */ if (~0 == sw_if_index) { fib_node_index_t fib_entry_index; u32 fib_index; fib_index = ip6_fib_index_from_table_id (table_id); if (~0 == fib_index) { vlib_buffer_free (vm, &bi0, 1); return SEND_PING_NO_TABLE; } fib_entry_index = ip6_fib_table_lookup (fib_index, pa6, 128); sw_if_index = fib_entry_get_resolving_interface (fib_entry_index); /* * Set the TX interface to force ip-lookup to use its table ID */ vnet_buffer (p0)->sw_if_index[VLIB_TX] = fib_index; } else { /* * force an IP lookup in the table bound to the user's chosen * source interface. */ vnet_buffer (p0)->sw_if_index[VLIB_TX] = ip6_fib_table_get_index_for_sw_if_index (sw_if_index); } if (~0 == sw_if_index) { vlib_buffer_free (vm, &bi0, 1); return SEND_PING_NO_INTERFACE; } vnet_buffer (p0)->sw_if_index[VLIB_RX] = sw_if_index; h0 = vlib_buffer_get_current (p0); /* Fill in ip6 header fields */ h0->ip6.ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (0x6 << 28); h0->ip6.payload_length = 0; /* Set below */ h0->ip6.protocol = IP_PROTOCOL_ICMP6; h0->ip6.hop_limit = 255; h0->ip6.dst_address = *pa6; h0->ip6.src_address = *pa6; /* Fill in the correct source now */ ip6_address_t *a = ip6_interface_first_address (im, sw_if_index); h0->ip6.src_address = a[0]; /* Fill in icmp fields */ h0->icmp.type = ICMP6_echo_request; h0->icmp.code = 0; h0->icmp.checksum = 0; data_len = init_icmp46_echo_request (&h0->icmp_echo, seq_host, id_host, data_len); h0->icmp_echo.time_sent = vlib_time_now (vm); /* Fix up the lengths */ h0->ip6.payload_length = clib_host_to_net_u16 (data_len + sizeof (icmp46_header_t)); p0->current_length = clib_net_to_host_u16 (h0->ip6.payload_length) + STRUCT_OFFSET_OF (icmp6_echo_request_header_t, icmp); /* Calculate the ICMP checksum */ h0->icmp.checksum = 0; h0->icmp.checksum = ip6_tcp_udp_icmp_compute_checksum (vm, 0, &h0->ip6, &bogus_length); /* Enqueue the packet right now */ f = vlib_get_frame_to_node (vm, ip6_lookup_node.index); to_next = vlib_frame_vector_args (f); to_next[0] = bi0; f->n_vectors = 1; vlib_put_frame_to_node (vm, ip6_lookup_node.index, f); return SEND_PING_OK; } static send_ip46_ping_result_t send_ip4_ping (vlib_main_t * vm, ip4_main_t * im, u32 table_id, ip4_address_t * pa4, u32 sw_if_index, u16 seq_host, u16 id_host, u16 data_len, u8 verbose) { icmp4_echo_request_header_t *h0; u32 bi0 = 0; ip_lookup_main_t *lm = &im->lookup_main; vlib_buffer_t *p0; vlib_frame_t *f; u32 *to_next; u32 if_add_index0; if (vlib_buffer_alloc (vm, &bi0, 1) != 1) return SEND_PING_ALLOC_FAIL; p0 = vlib_get_buffer (vm, bi0); /* * if the user did not provide a source interface, use the any interface * that the destination resolves via. */ if (~0 == sw_if_index) { fib_node_index_t fib_entry_index; u32 fib_index; fib_index = ip4_fib_index_from_table_id (table_id); if (~0 == fib_index) { vlib_buffer_free (vm, &bi0, 1); return SEND_PING_NO_TABLE; } fib_entry_index = ip4_fib_table_lookup (ip4_fib_get (fib_index), pa4, 32); sw_if_index = fib_entry_get_resolving_interface (fib_entry_index); /* * Set the TX interface to force ip-lookup to use the user's table ID */ vnet_buffer (p0)->sw_if_index[VLIB_TX] = fib_index; } else { /* * force an IP lookup in the table bound to the user's chosen * source interface. */ vnet_buffer (p0)->sw_if_index[VLIB_TX] = ip4_fib_table_get_index_for_sw_if_index (sw_if_index); } if (~0 == sw_if_index) { vlib_buffer_free (vm, &bi0, 1); return SEND_PING_NO_INTERFACE; } vnet_buffer (p0)->sw_if_index[VLIB_RX] = sw_if_index; h0 = vlib_buffer_get_current (p0); /* Fill in ip4 header fields */ h0->ip4.checksum = 0; h0->ip4.ip_version_and_header_length = 0x45; h0->ip4.tos = 0; h0->ip4.length = 0; /* Set below */ h0->ip4.fragment_id = 0; h0->ip4.flags_and_fragment_offset = 0; h0->ip4.ttl = 0xff; h0->ip4.protocol = IP_PROTOCOL_ICMP; h0->ip4.dst_address = *pa4; h0->ip4.src_address = *pa4; /* Fill in the correct source now */ if_add_index0 = lm->if_address_pool_index_by_sw_if_index[sw_if_index]; if (PREDICT_TRUE (if_add_index0 != ~0)) { ip_interface_address_t *if_add = pool_elt_at_index (lm->if_address_pool, if_add_index0); ip4_address_t *if_ip = ip_interface_address_get_address (lm, if_add); h0->ip4.src_address = *if_ip; if (verbose) { vlib_cli_output (vm, "Source address: %U", format_ip4_address, &h0->ip4.src_address); } } /* Fill in icmp fields */ h0->icmp.type = ICMP4_echo_request; h0->icmp.code = 0; h0->icmp.checksum = 0; data_len = init_icmp46_echo_request (&h0->icmp_echo, seq_host, id_host, data_len); h0->icmp_echo.time_sent = vlib_time_now (vm); /* Fix up the lengths */ h0->ip4.length = clib_host_to_net_u16 (data_len + sizeof (icmp46_header_t) + sizeof (ip4_header_t)); p0->current_length = clib_net_to_host_u16 (h0->ip4.length); /* Calculate the IP and ICMP checksums */ h0->ip4.checksum = ip4_header_checksum (&(h0->ip4)); h0->icmp.checksum = ~ip_csum_fold (ip_incremental_checksum (0, &(h0->icmp), p0->current_length - sizeof (ip4_header_t))); /* Enqueue the packet right now */ f = vlib_get_frame_to_node (vm, ip4_lookup_node.index); to_next = vlib_frame_vector_args (f); to_next[0] = bi0; f->n_vectors = 1; vlib_put_frame_to_node (vm, ip4_lookup_node.index, f); return SEND_PING_OK; } static void print_ip6_icmp_reply (vlib_main_t * vm, u32 bi0) { vlib_buffer_t *b0 = vlib_get_buffer (vm, bi0); icmp6_echo_request_header_t *h0 = vlib_buffer_get_current (b0); f64 rtt = vlib_time_now (vm) - h0->icmp_echo.time_sent; vlib_cli_output (vm, "%d bytes from %U: icmp_seq=%d ttl=%d time=%.4f ms", clib_host_to_net_u16 (h0->ip6.payload_length), format_ip6_address, &h0->ip6.src_address, clib_host_to_net_u16 (h0->icmp_echo.seq), h0->ip6.hop_limit, rtt * 1000.0); } static void print_ip4_icmp_reply (vlib_main_t * vm, u32 bi0) { vlib_buffer_t *b0 = vlib_get_buffer (vm, bi0); icmp4_echo_request_header_t *h0 = vlib_buffer_get_current (b0); f64 rtt = vlib_time_now (vm) - h0->icmp_echo.time_sent; u32 rcvd_icmp_len = clib_host_to_net_u16 (h0->ip4.length) - (4 * (0xF & h0->ip4.ip_version_and_header_length)); vlib_cli_output (vm, "%d bytes from %U: icmp_seq=%d ttl=%d time=%.4f ms", rcvd_icmp_len, format_ip4_address, &h0->ip4.src_address, clib_host_to_net_u16 (h0->icmp_echo.seq), h0->ip4.ttl, rtt * 1000.0); } /* * Perform the ping run with the given parameters in the current CLI process. * Depending on whether pa4 or pa6 is set, runs IPv4 or IPv6 ping. * The amusing side effect is of course if both are set, then both pings are sent. * This behavior can be used to ping a dualstack host over IPv4 and IPv6 at once. */ static void run_ping_ip46_address (vlib_main_t * vm, u32 table_id, ip4_address_t * pa4, ip6_address_t * pa6, u32 sw_if_index, f64 ping_interval, u32 ping_repeat, u32 data_len, u32 verbose) { int i; ping_main_t *pm = &ping_main; uword curr_proc = vlib_current_process (vm); u32 n_replies = 0; u32 n_requests = 0; ping_run_t *pr = 0; u32 ping_run_index = 0; u16 icmp_id; static u32 rand_seed = 0; if (PREDICT_FALSE (!rand_seed)) rand_seed = random_default_seed (); icmp_id = random_u32 (&rand_seed) & 0xffff; while (hash_get (pm->ping_run_by_icmp_id, icmp_id)) { vlib_cli_output (vm, "ICMP ID collision at %d, incrementing", icmp_id); icmp_id++; } pool_get (pm->ping_runs, pr); ping_run_index = pr - pm->ping_runs; pr->cli_process_id = curr_proc; pr->icmp_id = icmp_id; hash_set (pm->ping_run_by_icmp_id, icmp_id, ping_run_index); for (i = 1; i <= ping_repeat; i++) { f64 sleep_interval; f64 time_ping_sent = vlib_time_now (vm); /* Reset pr: running ping in other process could have changed pm->ping_runs */ pr = vec_elt_at_index (pm->ping_runs, ping_run_index); pr->curr_seq = i; if (pa6 && (SEND_PING_OK == send_ip6_ping (vm, ping_main.ip6_main, table_id, pa6, sw_if_index, i, icmp_id, data_len, verbose))) { n_requests++; } if (pa4 && (SEND_PING_OK == send_ip4_ping (vm, ping_main.ip4_main, table_id, pa4, sw_if_index, i, icmp_id, data_len, verbose))) { n_requests++; } while ((i <= ping_repeat) && ((sleep_interval = time_ping_sent + ping_interval - vlib_time_now (vm)) > 0.0)) { uword event_type, *event_data = 0; vlib_process_wait_for_event_or_clock (vm, sleep_interval); event_type = vlib_process_get_events (vm, &event_data); switch (event_type) { case ~0: /* no events => timeout */ break; case PING_RESPONSE_IP6: { int i; for (i = 0; i < vec_len (event_data); i++) { u32 bi0 = event_data[0]; print_ip6_icmp_reply (vm, bi0); n_replies++; if (0 != bi0) { vlib_buffer_free (vm, &bi0, 1); } } } break; case PING_RESPONSE_IP4: { int i; for (i = 0; i < vec_len (event_data); i++) { u32 bi0 = event_data[0]; print_ip4_icmp_reply (vm, bi0); n_replies++; if (0 != bi0) { vlib_buffer_free (vm, &bi0, 1); } } } break; default: /* someone pressed a key, abort */ vlib_cli_output (vm, "Aborted due to a keypress."); i = 1 + ping_repeat; break; } } } vlib_cli_output (vm, "\n"); { float loss = (0 == n_requests) ? 0 : 100.0 * ((float) n_requests - (float) n_replies) / (float) n_requests; vlib_cli_output (vm, "Statistics: %u sent, %u received, %f%% packet loss\n", n_requests, n_replies, loss); /* Reset pr: running ping in other process could have changed pm->ping_runs */ pr = vec_elt_at_index (pm->ping_runs, ping_run_index); hash_unset (pm->ping_run_by_icmp_id, icmp_id); pool_put (pm->ping_runs, pr); } } static clib_error_t * ping_ip_address (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { ip4_address_t a4; ip6_address_t a6; clib_error_t *error = 0; u32 ping_repeat = 5; u8 ping_ip4, ping_ip6; vnet_main_t *vnm = vnet_get_main (); u32 data_len = PING_DEFAULT_DATA_LEN; u32 verbose = 0; f64 ping_interval = PING_DEFAULT_INTERVAL; u32 sw_if_index, table_id; table_id = 0; ping_ip4 = ping_ip6 = 0; sw_if_index = ~0; if (unformat (input, "%U", unformat_ip4_address, &a4)) { ping_ip4 = 1; } else if (unformat (input, "%U", unformat_ip6_address, &a6)) { ping_ip6 = 1; } else if (unformat (input, "ipv4")) { if (unformat (input, "%U", unformat_ip4_address, &a4)) { ping_ip4 = 1; } else { error = clib_error_return (0, "expecting IPv4 address but got `%U'", format_unformat_error, input); } } else if (unformat (input, "ipv6")) { if (unformat (input, "%U", unformat_ip6_address, &a6)) { ping_ip6 = 1; } else { error = clib_error_return (0, "expecting IPv6 address but got `%U'", format_unformat_error, input); } } else { error = clib_error_return (0, "expecting IP4/IP6 address `%U'. Usage: ping <addr> [source <intf>] [size <datasz>] [repeat <count>] [verbose]", format_unformat_error, input); goto done; } /* allow for the second AF in the same ping */ if (!ping_ip4 && (unformat (input, "ipv4"))) { if (unformat (input, "%U", unformat_ip4_address, &a4)) { ping_ip4 = 1; } } else if (!ping_ip6 && (unformat (input, "ipv6"))) { if (unformat (input, "%U", unformat_ip6_address, &a6)) { ping_ip6 = 1; } } /* parse the rest of the parameters in a cycle */ while (!unformat_eof (input, NULL)) { if (unformat (input, "source")) { if (!unformat_user (input, unformat_vnet_sw_interface, vnm, &sw_if_index)) { error = clib_error_return (0, "unknown interface `%U'", format_unformat_error, input); goto done; } } else if (unformat (input, "size")) { if (!unformat (input, "%u", &data_len)) { error = clib_error_return (0, "expecting size but got `%U'", format_unformat_error, input); goto done; } } else if (unformat (input, "table-id")) { if (!unformat (input, "du", &table_id)) { error = clib_error_return (0, "expecting table-id but got `%U'", format_unformat_error, input); goto done; } } else if (unformat (input, "interval")) { if (!unformat (input, "%f", &ping_interval)) { error = clib_error_return (0, "expecting interval (floating point number) got `%U'", format_unformat_error, input); goto done; } } else if (unformat (input, "repeat")) { if (!unformat (input, "%u", &ping_repeat)) { error = clib_error_return (0, "expecting repeat count but got `%U'", format_unformat_error, input); goto done; } } else if (unformat (input, "verbose")) { verbose = 1; } else { error = clib_error_return (0, "unknown input `%U'", format_unformat_error, input); goto done; } } run_ping_ip46_address (vm, table_id, ping_ip4 ? &a4 : NULL, ping_ip6 ? &a6 : NULL, sw_if_index, ping_interval, ping_repeat, data_len, verbose); done: return error; } /*? * This command sends an ICMP ECHO_REQUEST to network hosts. The address * can be an IPv4 or IPv6 address (or both at the same time). * * @cliexpar * @parblock * Example of how ping an IPv4 address: * @cliexstart{ping 172.16.1.2 source GigabitEthernet2/0/0 repeat 2} * 64 bytes from 172.16.1.2: icmp_seq=1 ttl=64 time=.1090 ms * 64 bytes from 172.16.1.2: icmp_seq=2 ttl=64 time=.0914 ms * * Statistics: 2 sent, 2 received, 0% packet loss * @cliexend * * Example of how ping both an IPv4 address and IPv6 address at the same time: * @cliexstart{ping 172.16.1.2 ipv6 fe80::24a5:f6ff:fe9c:3a36 source GigabitEthernet2/0/0 repeat 2 verbose} * Adjacency index: 10, sw_if_index: 1 * Adj: ip6-discover-neighbor * Adj Interface: 0 * Forced set interface: 1 * Adjacency index: 0, sw_if_index: 4294967295 * Adj: ip4-miss * Adj Interface: 0 * Forced set interface: 1 * Source address: 172.16.1.1 * 64 bytes from 172.16.1.2: icmp_seq=1 ttl=64 time=.1899 ms * Adjacency index: 10, sw_if_index: 1 * Adj: ip6-discover-neighbor * Adj Interface: 0 * Forced set interface: 1 * Adjacency index: 0, sw_if_index: 4294967295 * Adj: ip4-miss * Adj Interface: 0 * Forced set interface: 1 * Source address: 172.16.1.1 * 64 bytes from 172.16.1.2: icmp_seq=2 ttl=64 time=.0910 ms * * Statistics: 4 sent, 2 received, 50% packet loss * @cliexend * @endparblock ?*/ /* *INDENT-OFF* */ VLIB_CLI_COMMAND (ping_command, static) = { .path = "ping", .function = ping_ip_address, .short_help = "ping {<ip-addr> | ipv4 <ip4-addr> | ipv6 <ip6-addr>}" " [ipv4 <ip4-addr> | ipv6 <ip6-addr>] [source <interface>]" " [size <pktsize>] [interval <sec>] [repeat <cnt>] [table-id <id>]" " [verbose]", }; /* *INDENT-ON* */ static clib_error_t * ping_cli_init (vlib_main_t * vm) { ping_main_t *pm = &ping_main; pm->ip6_main = &ip6_main; pm->ip4_main = &ip4_main; icmp6_register_type (vm, ICMP6_echo_reply, ip6_icmp_echo_reply_node.index); ip4_icmp_register_type (vm, ICMP4_echo_reply, ip4_icmp_echo_reply_node.index); return 0; } VLIB_INIT_FUNCTION (ping_cli_init); /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */