Skip to main content

asterust_junos/
bgp.rs

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