diff --git a/snapshots/frr_ospf_max_metric_router_lsa/validation/sickbay.yaml b/snapshots/frr_ospf_max_metric_router_lsa/validation/sickbay.yaml index 883fd008..440ad49e 100644 --- a/snapshots/frr_ospf_max_metric_router_lsa/validation/sickbay.yaml +++ b/snapshots/frr_ospf_max_metric_router_lsa/validation/sickbay.yaml @@ -10,4 +10,4 @@ entries: - hostname: ".*" test_name: test_bgp_rib_routes skip: - reason: Not Implemented + reason: Collected before lab_builder collected the BGP table diff --git a/snapshots/sonic_ebgp/validation/sickbay.yaml b/snapshots/sonic_ebgp/validation/sickbay.yaml deleted file mode 100644 index 29256d0b..00000000 --- a/snapshots/sonic_ebgp/validation/sickbay.yaml +++ /dev/null @@ -1,5 +0,0 @@ -entries: - - hostname: s1|s2 - test_name: test_bgp_rib_routes - skip: - reason: Not Implemented diff --git a/src/lab_builder/config.py b/src/lab_builder/config.py index f974010b..9a3f8275 100644 --- a/src/lab_builder/config.py +++ b/src/lab_builder/config.py @@ -355,6 +355,7 @@ class VendorProfile: "vtysh -c 'show ip route vrf all json'", "vtysh -c 'show ip ospf neighbor json'", "vtysh -c 'show ip ospf database'", + "vtysh -c 'show bgp vrf all ipv4 unicast json'", "vtysh -c 'show bgp vrf all summary json'", ], config_command="vtysh -c 'show running-config'", diff --git a/src/lab_validation/parsers/frr/commands/bgp_routes.py b/src/lab_validation/parsers/frr/commands/bgp_routes.py index 8b4686a0..ffe0071d 100644 --- a/src/lab_validation/parsers/frr/commands/bgp_routes.py +++ b/src/lab_validation/parsers/frr/commands/bgp_routes.py @@ -5,10 +5,15 @@ from ..models.routes import FrrBgpRoute, FrrBgpRouteNextHop AFI = "afi" +# Cumulus' FRR writes the AS path as "aspath" and the MED as "med"; FRR 10 +# writes them as "path" and "metric". ASPATH = "aspath" +ASPATH_FRR10 = "path" BESTPATH = "bestpath" IP = "ip" +LOCAL_PREF = "locPrf" MED = "med" +MED_FRR10 = "metric" MULTIPATH = "multipath" NEXTHOPS = "nexthops" ORIGIN = "origin" @@ -36,7 +41,7 @@ def _get_bgp_routes(vrf: str, json_obj: dict[Any, Any]) -> Sequence[FrrBgpRoute] routes_obj = json_obj[network] for path in routes_obj: - assert ASPATH in path + assert (ASPATH in path) != (ASPATH_FRR10 in path) assert NEXTHOPS in path assert ORIGIN in path assert PATH_FROM in path @@ -54,8 +59,9 @@ def _get_bgp_routes(vrf: str, json_obj: dict[Any, Any]) -> Sequence[FrrBgpRoute] origin=path[ORIGIN], path_from=path[PATH_FROM], peer_id=path[PEER_ID], - as_path=_get_as_path(path[ASPATH]), - med=path.get(MED, None), + as_path=_get_as_path(path.get(ASPATH, path.get(ASPATH_FRR10))), + med=path.get(MED, path.get(MED_FRR10)), + local_pref=path.get(LOCAL_PREF), weight=path[WEIGHT], next_hops=_get_next_hops(path[NEXTHOPS]), ) diff --git a/src/lab_validation/parsers/frr/models/routes.py b/src/lab_validation/parsers/frr/models/routes.py index 11f8f237..cc2ce004 100644 --- a/src/lab_validation/parsers/frr/models/routes.py +++ b/src/lab_validation/parsers/frr/models/routes.py @@ -45,5 +45,7 @@ class FrrBgpRoute: peer_id: str next_hops: Sequence[FrrBgpRouteNextHop] med: int | None = attr.ib(converter=optional_int_converter) + # Present only when the path carries LOCAL_PREF, i.e. from iBGP. + local_pref: int | None = attr.ib(converter=optional_int_converter, default=None) as_path: Sequence[int] weight: int diff --git a/src/lab_validation/validators/FrrValidator.py b/src/lab_validation/validators/FrrValidator.py index 1e238430..ee787932 100644 --- a/src/lab_validation/validators/FrrValidator.py +++ b/src/lab_validation/validators/FrrValidator.py @@ -1,16 +1,25 @@ +import math from collections.abc import Sequence from os import path from typing import AbstractSet, Any +from pybatfish.datamodel import NextHop, NextHopDiscard, NextHopInterface, NextHopIp + +from lab_validation.parsers.frr.commands.bgp_routes import ( + parse_show_ip_bgp_vrf_all_json, +) from lab_validation.parsers.frr.commands.routes import ( parse_show_ip_route_vrf_all_json_by_vrf, ) -from lab_validation.parsers.frr.models.routes import FrrIpRoute +from lab_validation.parsers.frr.models.routes import FrrBgpRoute, FrrIpRoute from lab_validation.validators.batfish_models.interface_properties import ( InterfaceProperties, ) +from lab_validation.validators.batfish_models.routes import BgpRibRoute from .CumulusFrrValidator import CumulusFrrValidator +from .utils.validation_utils import CostResult, match_pairs, matched_pairs_to_failures +from .vendor_validator import ValidationError # Linux interfaces outside the device config: the management port and the # docker bridge. Batfish does not model them. @@ -25,6 +34,27 @@ class FrrValidator(CumulusFrrValidator): local routes, are excluded. """ + SHOW_BGP_FILENAME_TXT = "vtysh_-c_'show_bgp_vrf_all_ipv4_unicast_json'.txt" + + def validate_bgp_rib_routes( + self, bgp_routes: Sequence[BgpRibRoute] + ) -> dict[Any, Any]: + """Compares the best and multipath IPv4 unicast paths in all VRFs.""" + show_bgp_path = path.join(self.device_path, FrrValidator.SHOW_BGP_FILENAME_TXT) + if not path.isfile(show_bgp_path): + raise ValidationError( + f"{FrrValidator.SHOW_BGP_FILENAME_TXT} was not collected" + ) + with open(show_bgp_path) as fp: + show_routes = parse_show_ip_bgp_vrf_all_json(fp.read()) + # Batfish's BGP RIB answer has only the paths it selected. + selected = [ + r for r in show_routes if r.is_valid and (r.is_bestpath or r.is_multipath) + ] + return matched_pairs_to_failures( + match_pairs(selected, bgp_routes, _diff_bgp_routes_cost) + ) + def validate_interface_properties( self, batfish_interfaces: Sequence[InterfaceProperties], @@ -56,3 +86,43 @@ def _show_route_processed( for r in super()._show_route_processed(show_routes) if r.next_hop_int not in HOST_ONLY_INTERFACES and r.protocol != "local" ] + + +def _diff_bgp_routes_cost( + show_route: FrrBgpRoute, batfish_route: BgpRibRoute +) -> CostResult: + if show_route.network != batfish_route.network: + return [("network", math.inf)] + if show_route.vrf != batfish_route.vrf: + return [("vrf", math.inf)] + + cost: CostResult = [] + protocol = "ibgp" if show_route.path_from == "internal" else "bgp" + if protocol != batfish_route.protocol: + cost.append(("protocol", 1.0)) + if show_route.origin.lower() != batfish_route.origin_type.lower(): + cost.append(("origin_type", 1.0)) + if tuple(show_route.as_path) != tuple(batfish_route.as_path): + cost.append(("as_path", 1.0)) + if (show_route.med or 0) != batfish_route.metric: + cost.append(("metric", 1.0)) + # FRR prints locPrf only for paths that carry LOCAL_PREF. + local_pref = 100 if show_route.local_pref is None else show_route.local_pref + if local_pref != batfish_route.local_preference: + cost.append(("local_preference", 1.0)) + if show_route.weight != batfish_route.weight: + cost.append(("weight", 1.0)) + cost += _bgp_next_hop_cost(show_route, batfish_route.next_hop) + return cost + + +def _bgp_next_hop_cost(show_route: FrrBgpRoute, next_hop: NextHop) -> CostResult: + used = [nh.ip for nh in show_route.next_hops if nh.is_used] + show_ip = used[0] if used else show_route.next_hops[0].ip + # FRR shows a path it originated with next hop 0.0.0.0 (or ::); Batfish + # with discard. + if show_ip in ("0.0.0.0", "::"): + return [] if isinstance(next_hop, NextHopDiscard) else [("next_hop", 1.0)] + if isinstance(next_hop, (NextHopIp, NextHopInterface)) and next_hop.ip == show_ip: + return [] + return [("next_hop", 1.0)] diff --git a/src/lab_validation/validators/test_FrrValidator.py b/src/lab_validation/validators/test_FrrValidator.py index 35cfcd15..c9c58ad2 100644 --- a/src/lab_validation/validators/test_FrrValidator.py +++ b/src/lab_validation/validators/test_FrrValidator.py @@ -1,11 +1,16 @@ from pathlib import Path +import pytest +from pybatfish.datamodel import NextHop, NextHopDiscard, NextHopIp + from lab_validation.parsers.frr.models.routes import FrrIpRoute from lab_validation.validators.batfish_models.interface_properties import ( InterfaceProperties, ) +from lab_validation.validators.batfish_models.routes import BgpRibRoute from .FrrValidator import FrrValidator +from .vendor_validator import ValidationError # Real output from a containerlab FRR 10.7.1 node, trimmed. SHOW_INTERFACE_VRF_ALL = """\ @@ -101,3 +106,88 @@ def test_show_route_processed_drops_local_and_management_routes( blackhole=False, ) ] + + +# Real output from a containerlab FRR 10.7.1 node, trimmed: a path the node +# originated, a best path learned over eBGP, and a valid path that lost. +SHOW_BGP_VRF_ALL_IPV4_UNICAST_JSON = """\ +{ +"default":{ + "vrfId": 0, + "vrfName": "default", + "routes": { "192.0.2.0/24": [{"valid":true,"bestpath":true, + "pathFrom":"external","prefix":"192.0.2.0","prefixLen":24,"metric":0, + "weight":32768,"peerId":"(unspec)","path":"","origin":"IGP", + "nexthops":[{"ip":"0.0.0.0","afi":"ipv4","used":true}]}], + "198.51.100.0/24": [{"valid":true,"bestpath":true,"pathFrom":"external", + "prefix":"198.51.100.0","prefixLen":24,"weight":0,"peerId":"10.0.23.0", + "path":"64500 64500","origin":"incomplete", + "nexthops":[{"ip":"10.0.23.0","afi":"ipv4","used":true}]}, + {"valid":true,"pathFrom":"external","prefix":"198.51.100.0", + "prefixLen":24,"weight":0,"peerId":"10.0.34.0","path":"64499 64601 64601", + "origin":"IGP","nexthops":[{"ip":"10.0.34.0","afi":"ipv4","used":true}]}] + } } +} +""" + + +def _bgp_validator(tmp_path: Path) -> FrrValidator: + (tmp_path / FrrValidator.SHOW_BGP_FILENAME_TXT).write_text( + SHOW_BGP_VRF_ALL_IPV4_UNICAST_JSON + ) + return FrrValidator(tmp_path) + + +def _batfish_bgp_route( + network: str, next_hop: NextHop, as_path: str, origin_type: str, weight: int +) -> BgpRibRoute: + return BgpRibRoute( + next_hop, + vrf="default", + network=network, + protocol="bgp", + as_path=as_path, + metric=0, + local_preference=100, + communities=[], + origin_protocol=None, + origin_type=origin_type, + weight=weight, + tag=None, + ) + + +def _batfish_bgp_routes(learned_as_path: str) -> list[BgpRibRoute]: + return [ + _batfish_bgp_route("192.0.2.0/24", NextHopDiscard(), "", "igp", 32768), + _batfish_bgp_route( + "198.51.100.0/24", + NextHopIp("10.0.23.0"), + learned_as_path, + "incomplete", + 0, + ), + ] + + +def test_validate_bgp_rib_routes_match(tmp_path: Path) -> None: + routes = _batfish_bgp_routes("64500 64500") + assert _bgp_validator(tmp_path).validate_bgp_rib_routes(routes) == {} + + +def test_validate_bgp_rib_routes_as_path_mismatch(tmp_path: Path) -> None: + routes = _batfish_bgp_routes("64500 64601") + failures = _bgp_validator(tmp_path).validate_bgp_rib_routes(routes) + assert len(failures) == 1 + assert "as_path" in next(iter(failures.values())) + + +def test_validate_bgp_rib_routes_missing_in_batfish(tmp_path: Path) -> None: + routes = _batfish_bgp_routes("64500 64500")[:1] + failures = _bgp_validator(tmp_path).validate_bgp_rib_routes(routes) + assert list(failures.values()) == ["No_match_found_on_the_right"] + + +def test_validate_bgp_rib_routes_not_collected(tmp_path: Path) -> None: + with pytest.raises(ValidationError, match="was not collected"): + FrrValidator(tmp_path).validate_bgp_rib_routes([]) diff --git a/tests/lab_validation/parsers/frr/commands/test_bgp_routes.py b/tests/lab_validation/parsers/frr/commands/test_bgp_routes.py index 3a0c6d81..b611da51 100644 --- a/tests/lab_validation/parsers/frr/commands/test_bgp_routes.py +++ b/tests/lab_validation/parsers/frr/commands/test_bgp_routes.py @@ -170,3 +170,67 @@ def test_parse_show_ip_bgp_vrf_all_json() -> None: weight=0, ), ] + + +def test_parse_show_bgp_vrf_all_ipv4_unicast_json_frr10() -> None: + # FRR 10 writes the AS path as "path", the MED as "metric" and, for iBGP + # paths, the local preference as "locPrf". + text = """ + { + "default":{ + "vrfId": 0, + "vrfName": "default", + "routerId": "1.1.1.1", + "localAS": 65001, + "routes": { "1.1.1.1/32": [{"valid":true,"bestpath":true, + "selectionReason":"First path received","pathFrom":"external", + "prefix":"1.1.1.1","prefixLen":32,"network":"1.1.1.1/32","version":1, + "metric":0,"weight":32768,"peerId":"(unspec)","path":"","origin":"IGP", + "nexthops":[{"ip":"0.0.0.0","hostname":"s1","afi":"ipv4","used":true}]}], + "2.2.2.2/32": [{"valid":true,"pathFrom":"internal","prefix":"2.2.2.2", + "prefixLen":32,"network":"2.2.2.2/32","version":4,"locPrf":200, + "weight":0,"peerId":"192.168.12.3","path":"65002 65003", + "origin":"incomplete", + "nexthops":[{"ip":"192.168.12.3","hostname":"s2","afi":"ipv4", + "used":true}]}] + } , "totalRoutes": 2, "totalPaths": 2 } + } + """ + assert parse_show_ip_bgp_vrf_all_json(text) == [ + FrrBgpRoute( + vrf="default", + network="1.1.1.1/32", + is_valid=True, + is_multipath=False, + is_bestpath=True, + origin="IGP", + path_from="external", + peer_id="(unspec)", + next_hops=[ + FrrBgpRouteNextHop(ip="0.0.0.0", afi="ipv4", scope=None, is_used=True) + ], + med=0, + local_pref=None, + as_path=(), + weight=32768, + ), + FrrBgpRoute( + vrf="default", + network="2.2.2.2/32", + is_valid=True, + is_multipath=False, + is_bestpath=False, + origin="incomplete", + path_from="internal", + peer_id="192.168.12.3", + next_hops=[ + FrrBgpRouteNextHop( + ip="192.168.12.3", afi="ipv4", scope=None, is_used=True + ) + ], + med=None, + local_pref=200, + as_path=(65002, 65003), + weight=0, + ), + ]