Skip to main content

asterust_junos/protocols/bgp/
mod.rs

1//! `bgp`
2//! `protocols { bgp { ... } }`.
3//!
4//! # See also
5//!
6//! - [bgp](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/bgp-edit-protocols.html)
7//! - [group (Protocols BGP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/group-edit-protocols-bgp.html)
8//! - [neighbor (Protocols BGP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/neighbor-edit-protocols-bgp.html)
9//! - [disable (Protocols BGP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/disable-edit-protocols-bgp.html)
10//! - [path-selection](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/path-selection-edit-protocols-bgp.html)
11//! - [multipath-build-priority](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/multipath-build-priority-edit-protocols-bgp.html)
12//! - [BGP Route Prioritization](https://networkingdocs.hpe.com/documentation/us/en/software/junos/bgp/topics/topic-map/bgp-route-prioritization.html)
13//! - [precision-timers](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/precision-timers-edit-protocols-bgp.html)
14
15mod dynamic_neighbor;
16mod family;
17mod group;
18mod neighbor;
19mod output_queue_priority;
20mod path_selection;
21mod peer_options;
22mod srv6;
23
24pub use dynamic_neighbor::{DynamicNeighbor, PeerAutoDiscovery};
25pub use family::{AddPath, AddPathSend, BgpFamily, EntropyLabel, FamilyGracefulRestart, PrefixLimit};
26pub use group::BgpGroup;
27pub use neighbor::BgpNeighbor;
28pub use output_queue_priority::OutputQueuePriority;
29pub use path_selection::PathSelection;
30pub use peer_options::{BgpBfd, BgpGracefulRestart, BgpMultipath, BgpPeerOptions, LocalAs, Multihop, RemovePrivate};
31pub(crate) use srv6::parse_srv6;
32pub use srv6::{BgpSrv6, BgpSrv6Locator, BgpSrv6MicroSid};
33
34use crate::{child_block, has_leaf, named_children, statement_words, top_level};
35use asterust::config::Config;
36use group::parse_group;
37use output_queue_priority::parse_output_queue_priority;
38use path_selection::parse_path_selection;
39use peer_options::parse_peer_options;
40
41/// The `protocols bgp` configuration.
42#[derive(Clone, Debug, PartialEq, Eq)]
43#[non_exhaustive]
44pub struct Bgp {
45    pub groups: Vec<BgpGroup>,
46    /// Peer options written directly under `bgp`, which every group inherits unless it overrides them.
47    pub options: BgpPeerOptions,
48    /// BGP is disabled on the system.
49    pub disable: bool,
50    pub precision_timers: bool,
51    pub path_selection: Option<PathSelection>,
52    pub output_queue_priority: Option<OutputQueuePriority>,
53    /// `low` or `medium`, from `multipath-build-priority`.
54    pub multipath_build_priority: Option<String>,
55    /// `source-packet-routing srv6`.
56    pub srv6: Option<BgpSrv6>,
57}
58
59/// Returns the `protocols bgp` block, or `None` if BGP is not configured.
60///
61/// # Examples
62///
63/// ```
64/// use asterust::config::juniper;
65/// use asterust_junos::protocols::bgp::bgp;
66///
67/// let config = juniper::parse_braces("protocols {\n    bgp {\n        group IBGP {\n            type internal;\n        }\n    }\n}\n");
68/// let bgp = bgp(&config).unwrap();
69/// assert_eq!(bgp.groups[0].name, "IBGP");
70/// assert_eq!(bgp.groups[0].group_type.as_deref(), Some("internal"));
71/// ```
72pub fn bgp(config: &Config) -> Option<Bgp> {
73    let bgp = child_block(top_level(config, "protocols")?, "bgp")?;
74    Some(Bgp {
75        groups: named_children(bgp, "group")
76            .map(|(name, group)| parse_group(name, group))
77            .collect(),
78        options: parse_peer_options(bgp),
79        disable: has_leaf(bgp, "disable"),
80        precision_timers: has_leaf(bgp, "precision-timers"),
81        path_selection: parse_path_selection(bgp),
82        output_queue_priority: parse_output_queue_priority(bgp),
83        multipath_build_priority: statement_words(bgp, "multipath-build-priority")
84            .and_then(|words| words.first().map(|word| word.to_string())),
85        srv6: parse_srv6(bgp),
86    })
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use asterust::config::juniper;
93
94    // Not from documentation: covers statements the Juniper examples do not use. See the README "Sources".
95    const CONFIG: &str = r#"
96protocols {
97    bgp {
98        group IBGP {
99            type internal;
100            local-address 10.255.0.1;
101            family inet {
102                unicast;
103            }
104            family inet-vpn {
105                unicast;
106            }
107            cluster 10.255.0.1;
108            export [ NEXT-HOP-SELF EXPORT-LOOPBACK ];
109            neighbor 10.255.0.2 {
110                description rr1;
111            }
112            neighbor 10.255.0.3;
113        }
114        group EBGP {
115            type external;
116            peer-as 65001;
117            import FROM-PEER;
118            neighbor 192.0.2.2 {
119                peer-as 65002;
120            }
121        }
122    }
123}
124"#;
125
126    #[test]
127    fn extracts_internal_group_with_reflector_settings() {
128        let bgp = bgp(&juniper::parse_braces(CONFIG)).unwrap();
129        assert_eq!(bgp.groups.len(), 2);
130
131        let ibgp = &bgp.groups[0];
132        assert_eq!(ibgp.name, "IBGP");
133        assert_eq!(ibgp.group_type.as_deref(), Some("internal"));
134        assert_eq!(ibgp.local_address.as_deref(), Some("10.255.0.1"));
135        assert_eq!(ibgp.cluster.as_deref(), Some("10.255.0.1"));
136        assert_eq!(ibgp.families, ["inet", "inet-vpn"]);
137        assert_eq!(ibgp.export_policies, ["NEXT-HOP-SELF", "EXPORT-LOOPBACK"]);
138        assert!(ibgp.import_policies.is_empty());
139
140        let addresses: Vec<_> = ibgp.neighbors.iter().map(|n| n.address.as_str()).collect();
141        assert_eq!(addresses, ["10.255.0.2", "10.255.0.3"]);
142        assert_eq!(ibgp.neighbors[0].description.as_deref(), Some("rr1"));
143        assert_eq!(ibgp.neighbors[1].description, None);
144    }
145
146    #[test]
147    fn external_group_and_neighbor_override() {
148        let bgp = bgp(&juniper::parse_braces(CONFIG)).unwrap();
149        let ebgp = &bgp.groups[1];
150        assert_eq!(ebgp.group_type.as_deref(), Some("external"));
151        assert_eq!(ebgp.peer_as.as_deref(), Some("65001"));
152        assert_eq!(ebgp.import_policies, ["FROM-PEER"]);
153        assert_eq!(ebgp.neighbors[0].peer_as.as_deref(), Some("65002"));
154    }
155
156    #[test]
157    fn no_bgp_is_none() {
158        assert!(bgp(&juniper::parse_braces("protocols {\n ospf {\n }\n}\n")).is_none());
159    }
160
161    // The DOC_* fixtures are adapted from Juniper's BGP User Guide; see the README "Sources".
162
163    // "BGP Peering Sessions", "Example: Configuring External BGP Point-to-Point Peer Sessions", Device E `show protocols`.
164    const DOC_EXTERNAL_PEERS: &str = r#"
165protocols {
166    bgp {
167        group external-peers {
168            type external;
169            peer-as 22;
170            neighbor 10.10.10.2;
171            neighbor 10.10.10.6;
172            neighbor 10.10.10.10;
173            neighbor 10.21.7.2 {
174                peer-as 79;
175            }
176        }
177    }
178}
179"#;
180
181    // "BGP Peering Sessions", "Example: Configuring Internal BGP Peer Sessions", Device A `show protocols`
182    // (the guide's typographic quotes around the description are written as plain quotes).
183    const DOC_INTERNAL_PEERS: &str = r#"
184protocols {
185    bgp {
186        group internal-peers {
187            type internal;
188            description "connections to B and C";
189            local-address 192.168.6.5;
190            export send-direct;
191            neighbor 192.163.6.4;
192            neighbor 192.168.40.4;
193        }
194    }
195}
196"#;
197
198    // "BGP Route Reflectors", "Example: Configuring a Route Reflector", Device A `show protocols`
199    // (the guide's rendering of this output drops a closing brace; it is restored here).
200    const DOC_ROUTE_REFLECTOR: &str = r#"
201protocols {
202    bgp {
203        group rr-clients {
204            type internal;
205            local-address 192.168.6.5;
206            export send-ospf;
207            cluster 192.168.6.5;
208            neighbor 192.163.6.4;
209            neighbor 192.168.40.4;
210        }
211        group non-clients {
212            type internal;
213            local-address 192.168.6.5;
214            export send-ospf;
215            neighbor 192.168.0.1;
216            neighbor 192.168.5.5;
217        }
218    }
219}
220"#;
221
222    // "BGP Peering Sessions", "Example: Configure Multiple Single-Hop EBGP Sessions on Different Links Using the
223    // Same IPv6 Link-Local Address", R1 `show protocols`.
224    const DOC_LINK_LOCAL: &str = r#"
225protocols {
226    bgp {
227        group external {
228            peer-as 65542;
229            local-as 65541;
230            neighbor "fe80::20%ge-0/0/1.1";
231            neighbor "fe80::20%ge-0/0/1.2";
232        }
233    }
234}
235"#;
236
237    #[test]
238    fn doc_external_peers_with_neighbor_level_peer_as() {
239        let bgp = bgp(&juniper::parse_braces(DOC_EXTERNAL_PEERS)).unwrap();
240        let group = &bgp.groups[0];
241        assert_eq!(group.name, "external-peers");
242        assert_eq!(group.group_type.as_deref(), Some("external"));
243        assert_eq!(group.peer_as.as_deref(), Some("22"));
244        let addresses: Vec<_> = group.neighbors.iter().map(|n| n.address.as_str()).collect();
245        assert_eq!(addresses, ["10.10.10.2", "10.10.10.6", "10.10.10.10", "10.21.7.2"]);
246        assert_eq!(group.neighbors[0].peer_as, None);
247        assert_eq!(group.neighbors[3].peer_as.as_deref(), Some("79"));
248    }
249
250    #[test]
251    fn doc_internal_peers_with_local_address_and_export() {
252        let bgp = bgp(&juniper::parse_braces(DOC_INTERNAL_PEERS)).unwrap();
253        let group = &bgp.groups[0];
254        assert_eq!(group.name, "internal-peers");
255        assert_eq!(group.group_type.as_deref(), Some("internal"));
256        assert_eq!(group.description.as_deref(), Some("connections to B and C"));
257        assert_eq!(group.local_address.as_deref(), Some("192.168.6.5"));
258        assert_eq!(group.export_policies, ["send-direct"]);
259        assert_eq!(group.neighbors.len(), 2);
260    }
261
262    #[test]
263    fn doc_route_reflector_cluster_marks_client_group() {
264        let bgp = bgp(&juniper::parse_braces(DOC_ROUTE_REFLECTOR)).unwrap();
265        assert_eq!(bgp.groups[0].name, "rr-clients");
266        assert_eq!(bgp.groups[0].cluster.as_deref(), Some("192.168.6.5"));
267        assert_eq!(bgp.groups[1].name, "non-clients");
268        assert_eq!(bgp.groups[1].cluster, None);
269        assert_eq!(bgp.groups[1].neighbors.len(), 2);
270    }
271
272    #[test]
273    fn doc_quoted_link_local_neighbors() {
274        let bgp = bgp(&juniper::parse_braces(DOC_LINK_LOCAL)).unwrap();
275        let group = &bgp.groups[0];
276        assert_eq!(group.peer_as.as_deref(), Some("65542"));
277        assert_eq!(group.local_as.as_deref(), Some("65541"));
278        let addresses: Vec<_> = group.neighbors.iter().map(|n| n.address.as_str()).collect();
279        assert_eq!(addresses, ["fe80::20%ge-0/0/1.1", "fe80::20%ge-0/0/1.2"]);
280    }
281}