summaryrefslogtreecommitdiff
path: root/src/op_mode/vpp.py
blob: 80697f5030937afa9cf5c37a0063259968a729b0 (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
#!/usr/bin/env python3
#
# Copyright VyOS maintainers and contributors <maintainers@vyos.io>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
import json
import typing

from tabulate import tabulate
from vyos.vpp import VPPControl
from vyos.vpp.utils import vpp_iface_name_transform
from vyos.configquery import ConfigTreeQuery
import vyos.opmode

NO_INDEX = 0xFFFFFFFF

class VPPShow:
    RX_STATES = {
        0: 'INITIALIZE',
        1: 'PORT_DISABLED',
        2: 'EXPIRED',
        3: 'LACP_DISABLED',
        4: 'DEFAULTED',
        5: 'CURRENT',
    }
    TX_STATES = {0: 'TRANSMIT'}
    MUX_STATES = {
        0: 'DETACHED',
        1: 'WAITING',
        2: 'ATTACHED',
        3: 'COLLECTING_DISTRIBUTING',
    }
    PTX_STATES = {0: 'NO_PERIODIC', 1: 'FAST', 2: 'SLOW', 3: 'PERIODIC_TX'}
    BOND_MODE = {
        1: 'round-robin',
        2: 'active-backup',
        3: 'xor',
        4: 'broadcast',
        5: 'lacp',
    }
    BOND_LB = {
        0: 'layer2',
        1: 'layer3+4',
        2: 'layer2+3',
        3: 'round-robin',
        4: 'broadcast',
        5: 'active-backup',
    }

    def __init__(self):
        self.config = ConfigTreeQuery()
        self.vpp = VPPControl()

    # -----------------------------
    # IPFIX Interfaces
    # -----------------------------
    def _get_ipfix_interfaces_raw(self) -> typing.List[dict]:
        interfaces = self.vpp.api.flowprobe_interface_dump()
        index_map = {
            i.sw_if_index: i.interface_name for i in self.vpp.api.sw_interface_dump()
        }

        return [
            {
                'interface': index_map.get(e.sw_if_index, f'if{e.sw_if_index}'),
                'sw_if_index': e.sw_if_index,
                'which': e.which.name.replace('FLOWPROBE_WHICH_', '').lower(),
                'direction': e.direction.name.replace(
                    'FLOWPROBE_DIRECTION_', ''
                ).lower(),
            }
            for e in interfaces
        ]

    def _show_ipfix_interfaces_formatted(self, data: typing.List[dict]) -> str:
        if not data:
            return 'No flowprobe interfaces configured.'
        table_data = [
            {
                'Interface': d['interface'],
                'VppIfIndex': d['sw_if_index'],
                'Flow-variant': d['which'],
                'Direction': d['direction'],
            }
            for d in data
        ]
        return tabulate(table_data, headers='keys', tablefmt='simple')

    def ipfix_interfaces(self, raw: bool):
        base = ['vpp', 'ipfix', 'interface']
        if not self.config.exists(base):
            raise vyos.opmode.UnconfiguredSubsystem(
                'vpp ipfix interface is not configured'
            )

        data = self._get_ipfix_interfaces_raw()
        return data if raw else self._show_ipfix_interfaces_formatted(data)

    # -----------------------------
    # IPFIX Collectors
    # -----------------------------
    def _get_ipfix_collectors_raw(self) -> typing.List[dict]:
        _, collectors = self.vpp.api.ipfix_all_exporter_get()
        return [
            {
                'collector_address': str(c.collector_address),
                'collector_port': c.collector_port,
                'src_address': str(c.src_address),
                'vrf_id': c.vrf_id,
                'path_mtu': c.path_mtu,
                'template_interval': c.template_interval,
                'udp_checksum': bool(c.udp_checksum),
            }
            for c in collectors
        ]

    def _show_ipfix_collectors_formatted(self, data: typing.List[dict]) -> str:
        if not data:
            return 'No IPFIX collectors configured.'
        table_data = [
            {
                'Collector': f"{d['collector_address']}:{d['collector_port']}",
                'Source': d['src_address'],
                'VRF': d['vrf_id'],
                'MTU': d['path_mtu'],
                'Template Intvl': d['template_interval'],
                'UDP Cksum': 'on' if d['udp_checksum'] else 'off',
            }
            for d in data
        ]
        return tabulate(table_data, headers='keys', tablefmt='simple')

    def ipfix_collectors(self, raw: bool):
        base = ['vpp', 'ipfix', 'collector']
        if not self.config.exists(base):
            raise vyos.opmode.UnconfiguredSubsystem(
                'vpp ipfix collector is not configured'
            )

        data = self._get_ipfix_collectors_raw()
        return data if raw else self._show_ipfix_collectors_formatted(data)

    # -----------------------------
    # IPFIX table
    # -----------------------------
    def _get_ipfix_table_raw(self):
        # VPP does not have API call to get this data
        data = self.vpp.cli_cmd('show flowprobe table')
        return [data.reply]

    def _show_ipfix_table_formatted(self) -> str:
        data = self.vpp.cli_cmd('show flowprobe table')
        return data.reply

    def ipfix_table(self, raw: bool):
        base = ['vpp', 'ipfix', 'collector']
        if not self.config.exists(base):
            raise vyos.opmode.UnconfiguredSubsystem(
                'vpp ipfix collector is not configured'
            )

        data = self._get_ipfix_table_raw()
        return data if raw else self._show_ipfix_table_formatted()

    # -----------------------------
    # Bonding information
    # -----------------------------
    def _get_raw_output(self, data_dump: typing.List[dict]) -> list[dict]:
        data = [json.loads(json.dumps(d._asdict(), default=str)) for d in data_dump]
        return data

    def _get_lacp_raw(self, ifname: typing.Optional[str]) -> list[dict]:
        lacp_dump = self.vpp.api.sw_interface_lacp_dump()
        data = self._get_raw_output(lacp_dump)

        if ifname:
            res = next((d for d in data if d['interface_name'] == ifname), None)
            if not res:
                raise vyos.opmode.IncorrectValue(
                    f'Interface {ifname} is not a member of any LACP bond'
                )
            data = [res]

        return data

    def _get_lacp_info_formatted(self, data):

        def bit(x, n):
            return (x >> n) & 1

        def bits_to_str(x):
            return ' '.join(f'{bit(x, n):3d}' for n in range(7, -1, -1))

        # Headers (exactly like VPP)
        print(f'{"":55} {"actor state":32} {"partner state":32}')
        print(
            'interface name'.ljust(26)
            + 'sw_if_index'.ljust(13)
            + 'bond interface'.ljust(17)
            + 'exp/def/dis/col/syn/agg/tim/act'.ljust(33)
            + 'exp/def/dis/col/syn/agg/tim/act'.ljust(32)
        )

        for d in data:
            iface = d['interface_name']
            sw_if = str(d['sw_if_index'])
            bond_if = d['bond_interface_name']
            actor_bits = bits_to_str(d['actor_state'])
            partner_bits = bits_to_str(d['partner_state'])

            print(
                f'{iface:25} {sw_if:12} {bond_if:16} {actor_bits:32} {partner_bits:32}'
            )

            # LAG ID formatting
            lag_line = (
                f'  LAG ID: '
                f'[({d["actor_system_priority"]:04x},{d["actor_system"].replace(":", "-")},'
                f'{d["actor_key"]:04x},{d["actor_port_priority"]:04x},{d["actor_port_number"]:04x}), '
                f'({d["partner_system_priority"]:04x},{d["partner_system"].replace(":", "-")},'
                f'{d["partner_key"]:04x},{d["partner_port_priority"]:04x},{d["partner_port_number"]:04x})]'
            )
            print(lag_line)

            # State machine line
            print(
                f'  RX-state: {self.RX_STATES[d["rx_state"]]}, '
                f'TX-state: {self.TX_STATES[d["tx_state"]]}, '
                f'MUX-state: {self.MUX_STATES[d["mux_state"]]}, '
                f'PTX-state: {self.PTX_STATES[d["ptx_state"]]}'
            )

    def _get_bond_raw(self, index: typing.Optional[str]) -> list[dict]:
        bond_dump = self.vpp.api.sw_bond_interface_dump(sw_if_index=index)

        result = []
        for bond in bond_dump:
            bond_info = {
                'interface_name': bond.interface_name,
                'sw_if_index': bond.sw_if_index,
                'mode': self.BOND_MODE[bond.mode],
                'hash_policy': self.BOND_LB[bond.lb],
                'active_members': bond.active_members,
                'members': {},
            }
            members = self.vpp.api.sw_member_interface_dump(
                sw_if_index=bond.sw_if_index
            )
            for member in members:
                bond_info['members'][member.interface_name] = {
                    'sw_if_index': member.sw_if_index,
                    'is_passive': member.is_passive,
                    'is_long_timeout': member.is_long_timeout,
                    'is_local_numa': member.is_local_numa,
                    'weight': member.weight,
                }
            result.append(bond_info)

        return result

    def _show_bond_info_formatted(self, data: typing.List[dict]) -> str:
        table_data = [
            {
                'Interface': d['interface_name'],
                'Mode': d['mode'],
                'Hash': d['hash_policy'],
                'Members': '\n'.join(sorted(d['members'].keys())),
                'Active members': d['active_members'],
            }
            for d in data
        ]
        return tabulate(table_data, headers='keys', tablefmt='simple', numalign='left')

    def lacp_info(self, raw: bool, ifname: typing.Optional[str]):
        data = self._get_lacp_raw(ifname)

        if not data:
            raise vyos.opmode.DataUnavailable(
                'No VPP interface is configured with LACP (802.3ad) mode'
            )

        if raw:
            return data

        return self._get_lacp_info_formatted(data)

    def lacp_details(self, raw: bool, ifname: typing.Optional[str]) -> str:
        # Check if interface is a part of any LACP bond
        self._get_lacp_raw(ifname)

        # VPP does not have API call to get this data
        cmd_command = f'show lacp{f" {ifname}" if ifname else ""} details'
        data = self.vpp.cli_cmd(cmd_command)

        if raw:
            return [data.reply]

        return data.reply

    def bond_info(self, raw: bool, ifname: typing.Optional[str]) -> str:
        index = NO_INDEX
        if ifname:
            if not ifname.startswith('vppbond') or not ifname[7:].isdigit():
                raise vyos.opmode.IncorrectValue(
                    f'"{ifname}" is not a valid bonding interface name (expected vppbondN)'
                )

            ifname_vpp = vpp_iface_name_transform(ifname)
            index = self.vpp.get_sw_if_index(ifname_vpp)
            if index is None:
                raise vyos.opmode.IncorrectValue(
                    f'Bonding interface {ifname} does not exist in VPP'
                )

        data = self._get_bond_raw(index)

        return data if raw else self._show_bond_info_formatted(data)

    def bond_details(self, raw: bool) -> str:
        # VPP API call is not so informative -> use CLI command
        cmd_command = 'show bond details'
        data = self.vpp.cli_cmd(cmd_command)
        return [data.reply] if raw else data.reply

    # -----------------------------
    # Bridge-domain information
    # -----------------------------
    def _parse_bridge_id(self, ifname: typing.Optional[str]) -> typing.Optional[int]:
        if ifname is None:
            return None

        if not ifname.startswith('vppbr') and not ifname[5:].isdigit():
            raise vyos.opmode.IncorrectValue(
                f'"{ifname}" is not a valid bridge interface name (expected vppbrN)'
            )

        if not self.config.exists(['interfaces', 'vpp', 'bridge', ifname]):
            raise vyos.opmode.IncorrectValue(
                f'Bridge interface {ifname} does not exist'
            )

        return int(ifname[5:])

    def _get_bridge_domain_raw(
        self, bd_id: typing.Optional[int] = None
    ) -> typing.List[dict]:
        # Dump bridge domains
        domains = self.vpp.api.bridge_domain_dump(
            bd_id=bd_id if bd_id is not None else NO_INDEX
        )

        result = []
        for d in domains:
            domain_info = {
                'bd_id': d.bd_id,
                'learning': bool(d.learn),
                'forward': bool(d.forward),
                'uu_flood': bool(d.uu_flood),
                'flood': bool(d.flood),
                'arp_term': bool(d.arp_term),
                'arp_ufwd': bool(d.arp_ufwd),
                'mac_age': d.mac_age,
                'bvi_interface': d.bvi_sw_if_index,
                'n_sw_ifs': d.n_sw_ifs,
                'members': [
                    {
                        'ifname': self.vpp.get_interface_name(m.sw_if_index),
                        'sw_if_index': m.sw_if_index,
                        'shg': m.shg,
                    }
                    for m in d.sw_if_details
                ],
            }
            result.append(domain_info)

        result.sort(key=lambda x: x['bd_id'])

        return result

    def _show_bridge_domain_formatted(self, data: typing.List[dict]) -> str:
        if not data:
            return 'No bridge domains configured.'

        table_data = [
            {
                'BD-ID': d['bd_id'],
                'Age(min)': 'off' if d['mac_age'] == 0 else d['mac_age'],
                'Learning': 'on' if d['learning'] else 'off',
                'U-Forwrd': 'on' if d['forward'] else 'off',
                'UU-Flood': 'flood' if d['uu_flood'] else 'drop',
                'Flooding': 'on' if d['flood'] else 'off',
                'ARP-Term': 'on' if d['arp_term'] else 'off',
                'arp-ufwd': 'on' if d['arp_ufwd'] else 'off',
                'BVI-Intf': (
                    self.vpp.get_interface_name(d['bvi_interface'])
                    if d['bvi_interface'] != NO_INDEX
                    else 'N/A'
                ),
            }
            for d in data
        ]
        return tabulate(table_data, headers='keys', tablefmt='simple', numalign='left')

    def bridge_domain(self, raw: bool, ifname: typing.Optional[str] = None):
        bd_id = self._parse_bridge_id(ifname)
        data = self._get_bridge_domain_raw(bd_id)
        return data if raw else self._show_bridge_domain_formatted(data)

    def bridge_domain_details(self, raw: bool, ifname: typing.List):
        bd_id = self._parse_bridge_id(ifname)

        # VPP API call is not so informative -> use CLI command
        cmd_command = f'show bridge-domain {bd_id} detail'
        data = self.vpp.cli_cmd(cmd_command)

        if raw:
            return [data.reply]

        return data.reply

    # -----------------------------
    # Runtime table
    # -----------------------------
    def _get_runtime_raw(self):
        # VPP does not have API call to get this data
        data = self.vpp.cli_cmd('show runtime')
        return [data.reply]

    def _show_runtime_formatted(self) -> str:
        data = self.vpp.cli_cmd('show runtime')
        return data.reply

    def runtime(self, raw: bool):
        data = self._get_runtime_raw()
        return data if raw else self._show_runtime_formatted()

    # -----------------------------
    # Interfaces mode
    # -----------------------------
    def mode(self, raw: bool):
        # VPP does not have API call to get this data
        data = self.vpp.cli_cmd('show mode')
        return [data.reply] if raw else data.reply


# -----------------------------
# VyOS IPFIX op-mode entries
# -----------------------------
@vyos.opmode.verify_cli_exists(['vpp', 'ipfix', 'interface'])
def show_ipfix_interfaces(raw: bool):
    return VPPShow().ipfix_interfaces(raw)

@vyos.opmode.verify_cli_exists(['vpp', 'ipfix', 'collector'])
def show_ipfix_collectors(raw: bool):
    return VPPShow().ipfix_collectors(raw)

@vyos.opmode.verify_cli_exists(['vpp', 'ipfix'])
def show_ipfix_table(raw: bool):
    return VPPShow().ipfix_table(raw)

# -----------------------------
# VPP Bonding information
# -----------------------------
@vyos.opmode.verify_cli_exists(['interfaces', 'vpp', 'bonding'])
def show_lacp(raw: bool, ifname: typing.Optional[str]):
    return VPPShow().lacp_info(raw, ifname)

@vyos.opmode.verify_cli_exists(['interfaces', 'vpp', 'bonding'])
def show_lacp_details(raw: bool, ifname: typing.Optional[str]):
    return VPPShow().lacp_details(raw, ifname)

@vyos.opmode.verify_cli_exists(['interfaces', 'vpp', 'bonding'])
def show_bond(raw: bool, ifname: typing.Optional[str]):
    return VPPShow().bond_info(raw, ifname)

@vyos.opmode.verify_cli_exists(['interfaces', 'vpp', 'bonding'])
def show_bond_details(raw: bool):
    return VPPShow().bond_details(raw)

# -----------------------------
# Bridge op-mode entry
# -----------------------------
@vyos.opmode.verify_cli_exists(['interfaces', 'vpp', 'bridge'])
def show_bridge(raw: bool, ifname: typing.Optional[str] = None):
    return VPPShow().bridge_domain(raw, ifname)

@vyos.opmode.verify_cli_exists(['interfaces', 'vpp', 'bridge'])
def show_bridge_details(raw: bool, ifname: typing.Optional[str] = None):
    return VPPShow().bridge_domain_details(raw, ifname)

# -----------------------------
# show runtime
# -----------------------------
@vyos.opmode.verify_cli_exists(['vpp'])
def show_runtime(raw: bool):
    return VPPShow().runtime(raw)

# -----------------------------
# show mode
# -----------------------------
@vyos.opmode.verify_cli_exists(['vpp'])
def show_mode(raw: bool):
    return VPPShow().mode(raw)


if __name__ == '__main__':
    try:
        res = vyos.opmode.run(sys.modules[__name__])
        if res:
            print(res)
    except (ValueError, vyos.opmode.Error) as e:
        print(e)
        sys.exit(1)