Skip to main content

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