aboutsummaryrefslogtreecommitdiffstats
path: root/test/vpp_pg_interface.py
blob: 3bcde9319a85c711ba6c13a26b15ab6104c028a9 (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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import os
import socket
from socket import inet_pton, inet_ntop
import struct
import time
from traceback import format_exc, format_stack

import scapy.compat
from scapy.utils import wrpcap, rdpcap, PcapReader
from scapy.plist import PacketList
from vpp_interface import VppInterface

from scapy.layers.l2 import Ether, ARP
from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
    ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
    IPv6ExtHdrHopByHop
from util import ppp, ppc
from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr


class CaptureTimeoutError(Exception):
    """ Exception raised if capture or packet doesn't appear within timeout """
    pass


def is_ipv6_misc(p):
    """ Is packet one of uninteresting IPv6 broadcasts? """
    if p.haslayer(ICMPv6ND_RA):
        if in6_ismaddr(p[IPv6].dst):
            return True
    if p.haslayer(IPv6ExtHdrHopByHop):
        for o in p[IPv6ExtHdrHopByHop].options:
            if isinstance(o, RouterAlert):
                return True
    return False


class VppPGInterface(VppInterface):
    """
    VPP packet-generator interface
    """

    @property
    def pg_index(self):
        """packet-generator interface index assigned by VPP"""
        return self._pg_index

    @property
    def gso_enabled(self):
        """gso enabled on packet-generator interface"""
        if self._gso_enabled == 0:
            return "gso-disabled"
        return "gso-enabled"

    @property
    def gso_size(self):
        """gso size on packet-generator interface"""
        return self._gso_size

    @property
    def coalesce_is_enabled(self):
        """coalesce enabled on packet-generator interface"""
        if self._coalesce_enabled == 0:
            return "coalesce-disabled"
        return "coalesce-enabled"

    @property
    def out_path(self):
        """pcap file path - captured packets"""
        return self._out_path

    def get_in_path(self, worker):
        """ pcap file path - injected packets"""
        if worker is not None:
            return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index,
                                              worker)
        return "%s/pg%u_in.pcap" % (self.test.tempdir, self.pg_index)

    @property
    def capture_cli(self):
        """CLI string to start capture on this interface"""
        return self._capture_cli

    def get_cap_name(self, worker=None):
        """return capture name for this interface and given worker"""
        if worker is not None:
            return self._cap_name + "-worker%d" % worker
        return self._cap_name

    def get_input_cli(self, nb_replays=None, worker=None):
        """return CLI string to load the injected packets"""
        input_cli = "packet-generator new pcap %s source pg%u name %s" % (
            self.get_in_path(worker), self.pg_index, self.get_cap_name(worker))
        if nb_replays is not None:
            return "%s limit %d" % (input_cli, nb_replays)
        if worker is not None:
            return "%s worker %d" % (input_cli, worker)
        return input_cli

    @property
    def in_history_counter(self):
        """Self-incrementing counter used when renaming old pcap files"""
        v = self._in_history_counter
        self._in_history_counter += 1
        return v

    @property
    def out_history_counter(self):
        """Self-incrementing counter used when renaming old pcap files"""
        v = self._out_history_counter
        self._out_history_counter += 1
        return v

    def __init__(self, test, pg_index, gso, gso_size):
        """ Create VPP packet-generator interface """
        super().__init__(test)

        r = test.vapi.pg_create_interface(pg_index, gso, gso_size)
        self.set_sw_if_index(r.sw_if_index)

        self._in_history_counter = 0
        self._out_history_counter = 0
        self._out_assert_counter = 0
        self._pg_index = pg_index
        self._gso_enabled = gso
        self._gso_size = gso_size
        self._coalesce_enabled = 0
        self._out_file = "pg%u_out.pcap" % self.pg_index
        self._out_path = self.test.tempdir + "/" + self._out_file
        self._capture_cli = "packet-generator capture pg%u pcap %s" % (
            self.pg_index, self.out_path)
        self._cap_name = "pcap%u-sw_if_index-%s" % (
            self.pg_index, self.sw_if_index)

    def rename_old_pcap_file(self, path, counter):
        filename = os.path.basename(path)
        try:
            if os.path.isfile(path):
                name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % \
                    (self.test.tempdir,
                     time.time(),
                     self.name,
                     counter,
                     filename)
                self.test.logger.debug("Renaming %s->%s" %
                                       (path, name))
                os.rename(path, name)
        except OSError:
            self.test.logger.debug("OSError: Could not rename %s %s" %
                                   (path, filename))

    def enable_capture(self):
        """ Enable capture on this packet-generator interface
            of at most n packets.
            If n < 0, this is no limit
        """
        # disable the capture to flush the capture
        self.disable_capture()
        self.rename_old_pcap_file(self.out_path, self.out_history_counter)
        # FIXME this should be an API, but no such exists atm
        self.test.vapi.cli(self.capture_cli)
        self._pcap_reader = None

    def disable_capture(self):
        self.test.vapi.cli("%s disable" % self.capture_cli)

    def coalesce_enable(self):
        """ Enable packet coalesce on this packet-generator interface"""
        self._coalesce_enabled = 1
        self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index,
                                                            1)

    def coalesce_disable(self):
        """ Disable packet coalesce on this packet-generator interface"""
        self._coalesce_enabled = 0
        self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index,
                                                            0)

    def add_stream(self, pkts, nb_replays=None, worker=None):
        """
        Add a stream of packets to this packet-generator

        :param pkts: iterable packets

        """
        wrpcap(self.get_in_path(worker), pkts)
        self.test.register_pcap(self, worker)
        # FIXME this should be an API, but no such exists atm
        self.test.vapi.cli(self.get_input_cli(nb_replays, worker))

    def generate_debug_aid(self, kind):
        """ Create a hardlink to the out file with a counter and a file
        containing stack trace to ease debugging in case of multiple capture
        files present. """
        self.test.logger.debug("Generating debug aid for %s on %s" %
                               (kind, self._name))
        link_path, stack_path = ["%s/debug_%s_%s_%s.%s" %
                                 (self.test.tempdir, self._name,
                                  self._out_assert_counter, kind, suffix)
                                 for suffix in ["pcap", "stack"]
                                 ]
        os.link(self.out_path, link_path)
        with open(stack_path, "w") as f:
            f.writelines(format_stack())
        self._out_assert_counter += 1

    def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
        """ Helper method to get capture and filter it """
        try:
            if not self.wait_for_capture_file(timeout):
                return None
            output = rdpcap(self.out_path)
            self.test.logger.debug("Capture has %s packets" % len(output.res))
        except:
            self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" %
                                   (self.out_path, format_exc()))
            return None
        before = len(output.res)
        if filter_out_fn:
            output.res = [p for p in output.res if not filter_out_fn(p)]
        removed = before - len(output.res)
        if removed:
            self.test.logger.debug(
                "Filtered out %s packets from capture (returning %s)" %
                (removed, len(output.res)))
        return output

    def get_capture(self, expected_count=None, remark=None, timeout=1,
                    filter_out_fn=is_ipv6_misc):
        """ Get captured packets

        :param expected_count: expected number of packets to capture, if None,
                               then self.test.packet_count_for_dst_pg_idx is
                               used to lookup the expected count
        :param remark: remark printed into debug logs
        :param timeout: how long to wait for packets
        :param filter_out_fn: filter applied to each packet, packets for which
                              the filter returns True are removed from capture
        :returns: iterable packets
        """
        remaining_time = timeout
        capture = None
        name = self.name if remark is None else "%s (%s)" % (self.name, remark)
        based_on = "based on provided argument"
        if expected_count is None:
            expected_count = \
                self.test.get_packet_count_for_if_idx(self.sw_if_index)
            based_on = "based on stored packet_infos"
            if expected_count == 0:
                raise Exception(
                    "Internal error, expected packet count for %s is 0!" %
                    name)
        self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % (
            expected_count, based_on, name))
        while remaining_time > 0:
            before = time.time()
            capture = self._get_capture(remaining_time, filter_out_fn)
            elapsed_time = time.time() - before
            if capture:
                if len(capture.res) == expected_count:
                    # bingo, got the packets we expected
                    return capture
                elif len(capture.res) > expected_count:
                    self.test.logger.error(
                        ppc("Unexpected packets captured:", capture))
                    break
                else:
                    self.test.logger.debug("Partial capture containing %s "
                                           "packets doesn't match expected "
                                           "count %s (yet?)" %
                                           (len(capture.res), expected_count))
            elif expected_count == 0:
                # bingo, got None as we expected - return empty capture
                return PacketList()
            remaining_time -= elapsed_time
        if capture:
            self.generate_debug_aid("count-mismatch")
            raise Exception("Captured packets mismatch, captured %s packets, "
                            "expected %s packets on %s" %
                            (len(capture.res), expected_count, name))
        else:
            raise Exception("No packets captured on %s" % name)

    def assert_nothing_captured(self, remark=None, filter_out_fn=is_ipv6_misc):
        """ Assert that nothing unfiltered was captured on interface

        :param remark: remark printed into debug logs
        :param filter_out_fn: filter applied to each packet, packets for which
                              the filter returns True are removed from capture
        """
        if os.path.isfile(self.out_path):
            try:
                capture = self.get_capture(
                    0, remark=remark, filter_out_fn=filter_out_fn)
                if not capture or len(capture.res) == 0:
                    # junk filtered out, we're good
                    return
            except:
                pass
            self.generate_debug_aid("empty-assert")
            if remark:
                raise AssertionError(
                    "Non-empty capture file present for interface %s (%s)" %
                    (self.name, remark))
            else:
                raise AssertionError("Capture file present for interface %s" %
                                     self.name)

    def wait_for_pg_stop(self):
        # wait till packet-generator is stopped
        # "show packet-generator" while it is still running gives this:
        # Name               Enabled        Count     Parameters
        # pcap0-sw_if_inde     Yes           64       limit 64, ...
        #
        # also have a 5-minute timeout just in case things go terribly wrong...
        deadline = time.time() + 300
        while self.test.vapi.cli('show packet-generator').find("Yes") != -1:
            self._test.sleep(0.01)  # yield
            if time.time() > deadline:
                self.test.logger.debug("Timeout waiting for pg to stop")
                break

    def wait_for_capture_file(self, timeout=1):
        """
        Wait until pcap capture file appears

        :param timeout: How long to wait for the packet (default 1s)

        :returns: True/False if the file is present or appears within timeout
        """
        self.wait_for_pg_stop()
        deadline = time.time() + timeout
        if not os.path.isfile(self.out_path):
            self.test.logger.debug("Waiting for capture file %s to appear, "
                                   "timeout is %ss" % (self.out_path, timeout))
        else:
            self.test.logger.debug("Capture file %s already exists" %
                                   self.out_path)
            return True
        while time.time() < deadline:
            if os.path.isfile(self.out_path):
                break
            self._test.sleep(0)  # yield
        if os.path.isfile(self.out_path):
            self.test.logger.debug("Capture file appeared after %fs" %
                                   (time.time() - (deadline - timeout)))
        else:
            self.test.logger.debug("Timeout - capture file still nowhere")
            return False
        return True

    def verify_enough_packet_data_in_pcap(self):
        """
        Check if enough data is available in file handled by internal pcap
        reader so that a whole packet can be read.

        :returns: True if enough data present, else False
        """
        orig_pos = self._pcap_reader.f.tell()  # save file position
        enough_data = False
        # read packet header from pcap
        packet_header_size = 16
        caplen = None
        end_pos = None
        hdr = self._pcap_reader.f.read(packet_header_size)
        if len(hdr) == packet_header_size:
            # parse the capture length - caplen
            sec, usec, caplen, wirelen = struct.unpack(
                self._pcap_reader.endian + "IIII", hdr)
            self._pcap_reader.f.seek(0, 2)  # seek to end of file
            end_pos = self._pcap_reader.f.tell()  # get position at end
            if end_pos >= orig_pos + len(hdr) + caplen:
                enough_data = True  # yay, we have enough data
        self._pcap_reader.f.seek(orig_pos, 0)  # restore original position
        return enough_data

    def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
        """
        Wait for next packet captured with a timeout

        :param timeout: How long to wait for the packet

        :returns: Captured packet if no packet arrived within timeout
        :raises Exception: if no packet arrives within timeout
        """
        deadline = time.time() + timeout
        if self._pcap_reader is None:
            if not self.wait_for_capture_file(timeout):
                raise CaptureTimeoutError("Capture file %s did not appear "
                                          "within timeout" % self.out_path)
            while time.time() < deadline:
                try:
                    self._pcap_reader = PcapReader(self.out_path)
                    break
                except:
                    self.test.logger.debug(
                        "Exception in scapy.PcapReader(%s): %s" %
                        (self.out_path, format_exc()))
        if not self._pcap_reader:
            raise CaptureTimeoutError("Capture file %s did not appear within "
                                      "timeout" % self.out_path)

        poll = False
        if timeout > 0:
            self.test.logger.debug("Waiting for packet")
        else:
            poll = True
            self.test.logger.debug("Polling for packet")
        while time.time() < deadline or poll:
            if not self.verify_enough_packet_data_in_pcap():
                self._test.sleep(0)  # yield
                poll = False
                continue
            p = self._pcap_reader.recv()
            if p is not None:
                if filter_out_fn is not None and filter_out_fn(p):
                    self.test.logger.debug(
                        "Packet received after %ss was filtered out" %
                        (time.time() - (deadline - timeout)))
                else:
                    self.test.logger.debug(
                        "Packet received after %fs" %
                        (time.time() - (deadline - timeout)))
                    return p
            self._test.sleep(0)  # yield
            poll = False
        self.test.logger.debug("Timeout - no packets received")
        raise CaptureTimeoutError("Packet didn't arrive within timeout")

    def create_arp_req(self):
        """Create ARP request applicable for this interface"""
        return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
                ARP(op=ARP.who_has, pdst=self.local_ip4,
                    psrc=self.remote_ip4, hwsrc=self.remote_mac))

    def create_ndp_req(self, addr=None):
        """Create NDP - NS applicable for this interface"""
        if not addr:
            addr = self.local_ip6
        nsma = in6_getnsma(inet_pton(socket.AF_INET6, addr))
        d = inet_ntop(socket.AF_INET6, nsma)

        return (Ether(dst=in6_getnsmac(nsma)) /
                IPv6(dst=d, src=self.remote_ip6) /
                ICMPv6ND_NS(tgt=addr) /
                ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))

    def resolve_arp(self, pg_interface=None):
        """Resolve ARP using provided packet-generator interface

        :param pg_interface: interface used to resolve, if None then this
            interface is used

        """
        if pg_interface is None:
            pg_interface = self
        self.test.logger.info("Sending ARP request for %s on port %s" %
                              (self.local_ip4, pg_interface.name))
        arp_req = self.create_arp_req()
        pg_interface.add_stream(arp_req)
        pg_interface.enable_capture()
        self.test.pg_start()
        self.test.logger.info(self.test.vapi.cli("show trace"))
        try:
            captured_packet = pg_interface.wait_for_packet(1)
        except:
            self.test.logger.info("No ARP received on port %s" %
                                  pg_interface.name)
            return
        arp_reply = captured_packet.copy()  # keep original for exception
        try:
            if arp_reply[ARP].op == ARP.is_at:
                self.test.logger.info("VPP %s MAC address is %s " %
                                      (self.name, arp_reply[ARP].hwsrc))
                self._local_mac = arp_reply[ARP].hwsrc
            else:
                self.test.logger.info("No ARP received on port %s" %
                                      pg_interface.name)
        except:
            self.test.logger.error(
                ppp("Unexpected response to ARP request:", captured_packet))
            raise

    def resolve_ndp(self, pg_interface=None, timeout=1, link_layer=False):
        """Resolve NDP using provided packet-generator interface

        :param pg_interface: interface used to resolve, if None then this
            interface is used
        :param timeout: how long to wait for response before giving up
        :param link_layer: resolve for global address if False (default)
            or for link-layer address if True

        """
        if pg_interface is None:
            pg_interface = self
        addr = self.local_ip6_ll if link_layer else self.local_ip6
        self.test.logger.info("Sending NDP request for %s on port %s" %
                              (addr, pg_interface.name))
        ndp_req = self.create_ndp_req(addr)
        pg_interface.add_stream(ndp_req)
        pg_interface.enable_capture()
        self.test.pg_start()
        now = time.time()
        deadline = now + timeout
        # Enabling IPv6 on an interface can generate more than the
        # ND reply we are looking for (namely MLD). So loop through
        # the replies to look for want we want.
        while now < deadline:
            try:
                captured_packet = pg_interface.wait_for_packet(
                    deadline - now, filter_out_fn=None)
            except:
                self.test.logger.error(
                    "Timeout while waiting for NDP response")
                raise
            ndp_reply = captured_packet.copy()  # keep original for exception
            try:
                ndp_na = ndp_reply[ICMPv6ND_NA]
                opt = ndp_na[ICMPv6NDOptDstLLAddr]
                self.test.logger.info("VPP %s MAC address is %s " %
                                      (self.name, opt.lladdr))
                self._local_mac = opt.lladdr
                self.test.logger.debug(self.test.vapi.cli("show trace"))
                # we now have the MAC we've been after
                return
            except:
                self.test.logger.info(
                    ppp("Unexpected response to NDP request:",
                        captured_packet))
            now = time.time()

        self.test.logger.debug(self.test.vapi.cli("show trace"))
        raise Exception("Timeout while waiting for NDP response")
n class="n">bif->dev_instance); // for return args->sw_if_index = bif->sw_if_index; args->rv = 0; } static clib_error_t * bond_create_command_fn (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { unformat_input_t _line_input, *line_input = &_line_input; bond_create_if_args_t args = { 0 }; u8 mode_is_set = 0; /* Get a line of input. */ if (!unformat_user (input, unformat_line_input, line_input)) return clib_error_return (0, "Missing required arguments."); args.id = ~0; args.mode = -1; args.lb = BOND_LB_L2; args.rv = -1; while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) { if (unformat (line_input, "mode %U", unformat_bond_mode, &args.mode)) mode_is_set = 1; else if (((args.mode == BOND_MODE_LACP) || (args.mode == BOND_MODE_XOR)) && unformat (line_input, "load-balance %U", unformat_bond_load_balance, &args.lb)) ; else if (unformat (line_input, "hw-addr %U", unformat_ethernet_address, args.hw_addr)) args.hw_addr_set = 1; else if (unformat (line_input, "id %u", &args.id)) ; else if (unformat (line_input, "gso")) args.gso = 1; else if (unformat (line_input, "numa-only")) { if (args.mode == BOND_MODE_LACP) args.numa_only = 1; else return clib_error_return (0, "Only lacp mode supports numa-only so far!"); } else return clib_error_return (0, "unknown input `%U'", format_unformat_error, input); } unformat_free (line_input); if (mode_is_set == 0) return clib_error_return (0, "Missing bond mode"); bond_create_if (vm, &args); if (!args.rv) vlib_cli_output (vm, "%U\n", format_vnet_sw_if_index_name, vnet_get_main (), args.sw_if_index); return args.error; } /* *INDENT-OFF* */ VLIB_CLI_COMMAND (bond_create_command, static) = { .path = "create bond", .short_help = "create bond mode {round-robin | active-backup | broadcast | " "{lacp | xor} [load-balance { l2 | l23 | l34 } [numa-only]]} " "[hw-addr <mac-address>] [id <if-id>] [gso]", .function = bond_create_command_fn, }; /* *INDENT-ON* */ static clib_error_t * bond_delete_command_fn (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { unformat_input_t _line_input, *line_input = &_line_input; u32 sw_if_index = ~0; vnet_main_t *vnm = vnet_get_main (); int rv; /* Get a line of input. */ if (!unformat_user (input, unformat_line_input, line_input)) return clib_error_return (0, "Missing <interface>"); while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) { if (unformat (line_input, "sw_if_index %d", &sw_if_index)) ; else if (unformat (line_input, "%U", unformat_vnet_sw_interface, vnm, &sw_if_index)) ; else return clib_error_return (0, "unknown input `%U'", format_unformat_error, input); } unformat_free (line_input); if (sw_if_index == ~0) return clib_error_return (0, "please specify interface name or sw_if_index"); rv = bond_delete_if (vm, sw_if_index); if (rv == VNET_API_ERROR_INVALID_SW_IF_INDEX) return clib_error_return (0, "not a bond interface"); else if (rv != 0) return clib_error_return (0, "error on deleting bond interface"); return 0; } /* *INDENT-OFF* */ VLIB_CLI_COMMAND (bond_delete__command, static) = { .path = "delete bond", .short_help = "delete bond {<interface> | sw_if_index <sw_idx>}", .function = bond_delete_command_fn, }; /* *INDENT-ON* */ void bond_add_member (vlib_main_t * vm, bond_add_member_args_t * args) { bond_main_t *bm = &bond_main; vnet_main_t *vnm = vnet_get_main (); bond_if_t *bif; member_if_t *mif; vnet_interface_main_t *im = &vnm->interface_main; vnet_hw_interface_t *bif_hw, *mif_hw; vnet_sw_interface_t *sw; u32 thread_index; u32 mif_if_index; bif = bond_get_bond_if_by_sw_if_index (args->group); if (!bif) { args->rv = VNET_API_ERROR_INVALID_INTERFACE; args->error = clib_error_return (0, "bond interface not found"); return; } // make sure the interface is not already added as member if (bond_get_member_by_sw_if_index (args->member)) { args->rv = VNET_API_ERROR_VALUE_EXIST; args->error = clib_error_return (0, "interface was already added as member"); return; } mif_hw = vnet_get_sup_hw_interface (vnm, args->member); if (mif_hw->dev_class_index == bond_dev_class.index) { args->rv = VNET_API_ERROR_INVALID_INTERFACE; args->error = clib_error_return (0, "bond interface cannot be added as member"); return; } if (bif->gso && !(mif_hw->flags & VNET_HW_INTERFACE_FLAG_SUPPORTS_GSO)) { args->rv = VNET_API_ERROR_INVALID_INTERFACE; args->error = clib_error_return (0, "member interface is not gso capable"); return; } if (bif->mode == BOND_MODE_LACP) { u8 *name = format (0, "/if/lacp/%u/%u/state%c", bif->sw_if_index, args->member, 0); vec_validate (bm->stats, bif->sw_if_index); vec_validate (bm->stats[bif->sw_if_index], args->member); args->error = stat_segment_register_state_counter (name, &bm->stats[bif->sw_if_index][args->member].actor_state); if (args->error != 0) { args->rv = VNET_API_ERROR_INVALID_INTERFACE; vec_free (name); return; } vec_reset_length (name); name = format (0, "/if/lacp/%u/%u/partner-state%c", bif->sw_if_index, args->member, 0); args->error = stat_segment_register_state_counter (name, &bm->stats[bif->sw_if_index][args->member].partner_state); vec_free (name); if (args->error != 0) { args->rv = VNET_API_ERROR_INVALID_INTERFACE; return; } } pool_get (bm->neighbors, mif); clib_memset (mif, 0, sizeof (*mif)); sw = pool_elt_at_index (im->sw_interfaces, args->member); /* port_enabled is both admin up and hw link up */ mif->port_enabled = vnet_sw_interface_is_up (vnm, sw->sw_if_index); mif->sw_if_index = sw->sw_if_index; mif->hw_if_index = sw->hw_if_index; mif->packet_template_index = (u8) ~ 0; mif->is_passive = args->is_passive; mif->group = args->group; mif->bif_dev_instance = bif->dev_instance; mif->mode = bif->mode; mif->is_long_timeout = args->is_long_timeout; if (args->is_long_timeout) mif->ttl_in_seconds = LACP_LONG_TIMOUT_TIME; else mif->ttl_in_seconds = LACP_SHORT_TIMOUT_TIME; vec_validate_aligned (bm->member_by_sw_if_index, mif->sw_if_index, CLIB_CACHE_LINE_BYTES); /* * mif - bm->neighbors may be 0 * Left shift it by 1 bit to distinguish the valid entry that we actually * store from the null entries */ bm->member_by_sw_if_index[mif->sw_if_index] = (uword) (((mif - bm->neighbors) << 1) | 1); vec_add1 (bif->members, mif->sw_if_index); mif_hw = vnet_get_sup_hw_interface (vnm, mif->sw_if_index); /* Save the old mac */ memcpy (mif->persistent_hw_address, mif_hw->hw_address, 6); bif_hw = vnet_get_sup_hw_interface (vnm, bif->sw_if_index); if (bif->use_custom_mac) { vnet_hw_interface_change_mac_address (vnm, mif_hw->hw_if_index, bif->hw_address); } else { // bond interface gets the mac address from the first member if (vec_len (bif->members) == 1) { memcpy (bif->hw_address, mif_hw->hw_address, 6); vnet_hw_interface_change_mac_address (vnm, bif_hw->hw_if_index, mif_hw->hw_address); } else { // subsequent members gets the mac address of the bond interface vnet_hw_interface_change_mac_address (vnm, mif_hw->hw_if_index, bif->hw_address); } } /* if there are secondary/virtual mac addrs, propagate to the member */ bond_member_add_del_mac_addrs (bif, mif->sw_if_index, 1 /* is_add */ ); if (bif_hw->l2_if_count) ethernet_set_flags (vnm, mif_hw->hw_if_index, ETHERNET_INTERFACE_FLAG_ACCEPT_ALL); else ethernet_set_flags (vnm, mif_hw->hw_if_index, /*ETHERNET_INTERFACE_FLAG_DEFAULT_L3 */ 0); if (bif->mode == BOND_MODE_LACP) { if (bm->lacp_enable_disable) (*bm->lacp_enable_disable) (vm, bif, mif, 1); } else if (mif->port_enabled) { bond_enable_collecting_distributing (vm, mif); } vec_foreach_index (thread_index, bm->per_thread_data) { bond_per_thread_data_t *ptd = vec_elt_at_index (bm->per_thread_data, thread_index); vec_validate_aligned (ptd->per_port_queue, vec_len (bif->members) - 1, CLIB_CACHE_LINE_BYTES); vec_foreach_index (mif_if_index, ptd->per_port_queue) { ptd->per_port_queue[mif_if_index].n_buffers = 0; } } args->rv = vnet_feature_enable_disable ("device-input", "bond-input", mif->sw_if_index, 1, 0, 0); if (args->rv) { args->error = clib_error_return (0, "Error encountered on input feature arc enable"); } } static clib_error_t * add_member_interface_command_fn (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { bond_add_member_args_t args = { 0 }; unformat_input_t _line_input, *line_input = &_line_input; vnet_main_t *vnm = vnet_get_main (); /* Get a line of input. */ if (!unformat_user (input, unformat_line_input, line_input)) return clib_error_return (0, "Missing required arguments."); args.member = ~0; args.group = ~0; while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) { if (unformat (line_input, "%U %U", unformat_vnet_sw_interface, vnm, &args.group, unformat_vnet_sw_interface, vnm, &args.member)) ; else if (unformat (line_input, "passive")) args.is_passive = 1; else if (unformat (line_input, "long-timeout")) args.is_long_timeout = 1; else { args.error = clib_error_return (0, "unknown input `%U'", format_unformat_error, input); break; } } unformat_free (line_input); if (args.error) return args.error; if (args.group == ~0) return clib_error_return (0, "Missing bond interface"); if (args.member == ~0) return clib_error_return (0, "please specify valid member interface name"); bond_add_member (vm, &args); return args.error; } /* *INDENT-OFF* */ VLIB_CLI_COMMAND (add_member_interface_command, static) = { .path = "bond add", .short_help = "bond add <BondEthernetx> <member-interface> " "[passive] [long-timeout]", .function = add_member_interface_command_fn, }; /* *INDENT-ON* */ void bond_detach_member (vlib_main_t * vm, bond_detach_member_args_t * args) { bond_if_t *bif; member_if_t *mif; mif = bond_get_member_by_sw_if_index (args->member); if (!mif) { args->rv = VNET_API_ERROR_INVALID_INTERFACE; args->error = clib_error_return (0, "interface was not a member"); return; } bif = bond_get_bond_if_by_dev_instance (mif->bif_dev_instance); bond_delete_neighbor (vm, bif, mif); } static clib_error_t * detach_interface_command_fn (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { bond_detach_member_args_t args = { 0 }; unformat_input_t _line_input, *line_input = &_line_input; vnet_main_t *vnm = vnet_get_main (); /* Get a line of input. */ if (!unformat_user (input, unformat_line_input, line_input)) return clib_error_return (0, "Missing required arguments."); args.member = ~0; while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) { if (unformat (line_input, "%U", unformat_vnet_sw_interface, vnm, &args.member)) ; else { args.error = clib_error_return (0, "unknown input `%U'", format_unformat_error, input); break; } } unformat_free (line_input); if (args.error) return args.error; if (args.member == ~0) return clib_error_return (0, "please specify valid member interface name"); bond_detach_member (vm, &args); return args.error; } /* *INDENT-OFF* */ VLIB_CLI_COMMAND (detach_interface_command, static) = { .path = "bond del", .short_help = "bond del <member-interface>", .function = detach_interface_command_fn, }; /* *INDENT-ON* */ static void show_bond (vlib_main_t * vm) { bond_main_t *bm = &bond_main; bond_if_t *bif; vlib_cli_output (vm, "%-16s %-12s %-13s %-13s %-14s %s", "interface name", "sw_if_index", "mode", "load balance", "active members", "members"); /* *INDENT-OFF* */ pool_foreach (bif, bm->interfaces, ({ vlib_cli_output (vm, "%-16U %-12d %-13U %-13U %-14u %u", format_bond_interface_name, bif->dev_instance, bif->sw_if_index, format_bond_mode, bif->mode, format_bond_load_balance, bif->lb, vec_len (bif->active_members), vec_len (bif->members)); })); /* *INDENT-ON* */ } static void show_bond_details (vlib_main_t * vm) { bond_main_t *bm = &bond_main; bond_if_t *bif; u32 *sw_if_index; /* *INDENT-OFF* */ pool_foreach (bif, bm->interfaces, ({ vlib_cli_output (vm, "%U", format_bond_interface_name, bif->dev_instance); vlib_cli_output (vm, " mode: %U", format_bond_mode, bif->mode); vlib_cli_output (vm, " load balance: %U", format_bond_load_balance, bif->lb); if (bif->gso) vlib_cli_output (vm, " gso enable"); if (bif->mode == BOND_MODE_ROUND_ROBIN) vlib_cli_output (vm, " last xmit member index: %u", bif->lb_rr_last_index); vlib_cli_output (vm, " number of active members: %d", vec_len (bif->active_members)); vec_foreach (sw_if_index, bif->active_members) { vlib_cli_output (vm, " %U", format_vnet_sw_if_index_name, vnet_get_main (), *sw_if_index); if (bif->mode == BOND_MODE_ACTIVE_BACKUP) { member_if_t *mif = bond_get_member_by_sw_if_index (*sw_if_index); if (mif) vlib_cli_output (vm, " weight: %u, is_local_numa: %u, " "sw_if_index: %u", mif->weight, mif->is_local_numa, mif->sw_if_index); } } vlib_cli_output (vm, " number of members: %d", vec_len (bif->members)); vec_foreach (sw_if_index, bif->members) { vlib_cli_output (vm, " %U", format_vnet_sw_if_index_name, vnet_get_main (), *sw_if_index); } vlib_cli_output (vm, " device instance: %d", bif->dev_instance); vlib_cli_output (vm, " interface id: %d", bif->id); vlib_cli_output (vm, " sw_if_index: %d", bif->sw_if_index); vlib_cli_output (vm, " hw_if_index: %d", bif->hw_if_index); })); /* *INDENT-ON* */ } static clib_error_t * show_bond_fn (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { u8 details = 0; while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { if (unformat (input, "details")) details = 1; else { return clib_error_return (0, "unknown input `%U'", format_unformat_error, input); } } if (details) show_bond_details (vm); else show_bond (vm); return 0; } /* *INDENT-OFF* */ VLIB_CLI_COMMAND (show_bond_command, static) = { .path = "show bond", .short_help = "show bond [details]", .function = show_bond_fn, }; /* *INDENT-ON* */ void bond_set_intf_weight (vlib_main_t * vm, bond_set_intf_weight_args_t * args) { member_if_t *mif; bond_if_t *bif; vnet_main_t *vnm; u32 old_weight; mif = bond_get_member_by_sw_if_index (args->sw_if_index); if (!mif) { args->rv = VNET_API_ERROR_INVALID_INTERFACE; args->error = clib_error_return (0, "Interface not a member"); return; } bif = bond_get_bond_if_by_dev_instance (mif->bif_dev_instance); if (!bif) { args->rv = VNET_API_ERROR_INVALID_INTERFACE; args->error = clib_error_return (0, "bond interface not found"); return; } if (bif->mode != BOND_MODE_ACTIVE_BACKUP) { args->rv = VNET_API_ERROR_INVALID_ARGUMENT; args->error = clib_error_return (0, "Weight valid for active-backup only"); return; } old_weight = mif->weight; mif->weight = args->weight; vnm = vnet_get_main (); /* * No need to sort the list if the affected member is not up (not in active * member set), active member count is 1, or the current member is already the * primary member and new weight > old weight. */ if (!vnet_sw_interface_is_up (vnm, mif->sw_if_index) || (vec_len (bif->active_members) == 1) || ((bif->active_members[0] == mif->sw_if_index) && (mif->weight >= old_weight))) return; bond_sort_members (bif); } static clib_error_t * bond_set_intf_cmd (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { bond_set_intf_weight_args_t args = { 0 }; u32 sw_if_index = (u32) ~ 0; unformat_input_t _line_input, *line_input = &_line_input; vnet_main_t *vnm = vnet_get_main (); u8 weight_enter = 0; u32 weight = 0; /* Get a line of input. */ if (!unformat_user (input, unformat_line_input, line_input)) return clib_error_return (0, "Missing required arguments."); while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) { if (unformat (line_input, "sw_if_index %d", &sw_if_index)) ; else if (unformat (line_input, "%U", unformat_vnet_sw_interface, vnm, &sw_if_index)) ; else if (unformat (line_input, "weight %u", &weight)) weight_enter = 1; else { clib_error_return (0, "unknown input `%U'", format_unformat_error, input); break; } } unformat_free (line_input); if (sw_if_index == (u32) ~ 0) { args.rv = VNET_API_ERROR_INVALID_INTERFACE; clib_error_return (0, "Interface name is invalid!"); } if (weight_enter == 0) { args.rv = VNET_API_ERROR_INVALID_ARGUMENT; clib_error_return (0, "weight missing"); } args.sw_if_index = sw_if_index; args.weight = weight; bond_set_intf_weight (vm, &args); return args.error; } /* *INDENT-OFF* */ VLIB_CLI_COMMAND(set_interface_bond_cmd, static) = { .path = "set interface bond", .short_help = "set interface bond <interface> | sw_if_index <idx>" " weight <value>", .function = bond_set_intf_cmd, }; /* *INDENT-ON* */ clib_error_t * bond_cli_init (vlib_main_t * vm) { bond_main_t *bm = &bond_main; bm->vlib_main = vm; bm->vnet_main = vnet_get_main (); vec_validate_aligned (bm->member_by_sw_if_index, 1, CLIB_CACHE_LINE_BYTES); vec_validate_aligned (bm->per_thread_data, vlib_get_thread_main ()->n_vlib_mains - 1, CLIB_CACHE_LINE_BYTES); return 0; } VLIB_INIT_FUNCTION (bond_cli_init); /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */