Skip to main content

asterust_junos/interfaces/
mod.rs

1//! `interfaces`
2//! `interfaces { ... }`.
3//!
4//! # See also
5//!
6//! - [`[edit interfaces]` hierarchy](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/topic-map/hierarchy-edit-interfaces.html)
7//! - [mtu (interfaces)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/mtu-edit-interfaces-ni.html)
8//! - [speed (Ethernet)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/speed-edit-interfaces-ethernet.html)
9//! - [encapsulation (interfaces)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/encapsulation-edit-interfaces-physical.html)
10//! - [vlan-tagging](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/vlan-tagging-edit-interfaces.html)
11//! - [flexible-vlan-tagging](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/flexible-vlan-tagging-edit-interfaces.html)
12//! - [native-vlan-id](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/native-vlan-id-edit-interfaces-qfx-series.html)
13//! - [per-unit-scheduler](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/per-unit-scheduler-edit-interfaces.html)
14//! - [no-gratuitous-arp-request](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-gratuitous-arp-request-edit-interfaces-port-security.html)
15
16mod aggregated_ether_options;
17mod auto_configure;
18mod esi;
19mod ether_options;
20mod hold_time;
21mod link_degrade_monitor;
22mod optics_options;
23mod otn_options;
24mod tca;
25mod unit;
26
27pub use aggregated_ether_options::{AggregatedEtherOptions, BfdDamping, BfdLivenessDetection, Lacp};
28pub use auto_configure::{AutoConfigure, AutoConfigureProfile, AutoConfigureRanges};
29pub use esi::{Esi, EsiAutoDerive, EsiDfElectionType, EsiDfGranularity, EsiPreference, EsiSystemMac};
30pub use ether_options::{EtherOptions, Ieee8023ad};
31pub use hold_time::HoldTime;
32pub use link_degrade_monitor::{LinkDegradeMonitor, LinkDegradeThresholds};
33pub use optics_options::{OpticsApplication, OpticsLowLight, OpticsOptions};
34pub use otn_options::{OduDelayManagement, OtnOptions, OtnRate, OtnTrigger, PreemptiveFastReroute, SignalDegrade};
35pub use tca::Tca;
36pub use unit::{
37    AddressArp, BandwidthThreshold, EthernetSwitching, FamilyFilter, FamilyPolicer, FamilySampling, InterfaceUnit,
38    RpfCheck, TrackedInterface, TrackedRoute, UnitAddress, UnitFamily, UnitTunnel, VlanMap, VlanTags, VrrpGroup,
39    VrrpInheritFrom, VrrpTrack,
40};
41
42use crate::{active_children, arg_of, child_block, has_leaf, named_children, top_level};
43use aggregated_ether_options::parse_aggregated_ether_options;
44use asterust::config::{Config, ConfigLine};
45use auto_configure::parse_auto_configure;
46use esi::parse_esi;
47use ether_options::parse_ether_options;
48use hold_time::parse_hold_time;
49use link_degrade_monitor::parse_link_degrade_monitor;
50use optics_options::parse_optics_options;
51use otn_options::parse_otn_options;
52use unit::parse_unit;
53
54/// A physical or loopback interface such as `ge-0/0/0` or `lo0`.
55#[derive(Clone, Debug, PartialEq, Eq)]
56#[non_exhaustive]
57pub struct Interface {
58    pub name: String,
59    pub description: Option<String>,
60    /// Set by the `disable` statement.
61    pub disabled: bool,
62    pub mtu: Option<String>,
63    /// e.g. `"1g"` or `"auto"`.
64    pub speed: Option<String>,
65    /// Physical encapsulation, e.g. `"flexible-ethernet-services"`.
66    pub encapsulation: Option<String>,
67    pub vlan_tagging: bool,
68    pub flexible_vlan_tagging: bool,
69    pub native_vlan_id: Option<String>,
70    pub per_unit_scheduler: bool,
71    pub no_gratuitous_arp_request: bool,
72    pub hold_time: Option<HoldTime>,
73    pub ether_options: Option<EtherOptions>,
74    pub aggregated_ether_options: Option<AggregatedEtherOptions>,
75    pub auto_configure: Option<AutoConfigure>,
76    pub optics_options: Option<OpticsOptions>,
77    pub otn_options: Option<OtnOptions>,
78    pub link_degrade_monitor: Option<LinkDegradeMonitor>,
79    pub esi: Option<Esi>,
80    pub units: Vec<InterfaceUnit>,
81}
82
83/// Returns every interface under the top-level `interfaces` block.
84///
85/// # Examples
86///
87/// ```
88/// use asterust::config::juniper;
89/// use asterust_junos::interfaces::interfaces;
90///
91/// let config = juniper::parse_braces("interfaces {\n    ge-0/0/0 {\n        mtu 9192;\n    }\n}\n");
92/// let found = interfaces(&config);
93/// assert_eq!(found[0].name, "ge-0/0/0");
94/// assert_eq!(found[0].mtu.as_deref(), Some("9192"));
95/// ```
96pub fn interfaces(config: &Config) -> Vec<Interface> {
97    let Some(root) = top_level(config, "interfaces") else {
98        return Vec::new();
99    };
100    // Interface names have no spaces; this skips `apply-groups`, `interface-range <x>` and similar.
101    active_children(root)
102        .filter(|c| !c.text.contains(' '))
103        .map(parse_interface)
104        .collect()
105}
106
107fn parse_interface(line: &ConfigLine) -> Interface {
108    Interface {
109        name: line.text.clone(),
110        description: arg_of(line, "description").map(str::to_string),
111        disabled: has_leaf(line, "disable"),
112        mtu: arg_of(line, "mtu").map(str::to_string),
113        speed: arg_of(line, "speed").map(str::to_string),
114        encapsulation: arg_of(line, "encapsulation").map(str::to_string),
115        vlan_tagging: has_leaf(line, "vlan-tagging"),
116        flexible_vlan_tagging: has_leaf(line, "flexible-vlan-tagging"),
117        native_vlan_id: arg_of(line, "native-vlan-id").map(str::to_string),
118        per_unit_scheduler: has_leaf(line, "per-unit-scheduler"),
119        no_gratuitous_arp_request: has_leaf(line, "no-gratuitous-arp-request"),
120        hold_time: parse_hold_time(line),
121        ether_options: parse_ether_options(line),
122        aggregated_ether_options: child_block(line, "aggregated-ether-options").map(parse_aggregated_ether_options),
123        auto_configure: child_block(line, "auto-configure").map(parse_auto_configure),
124        optics_options: child_block(line, "optics-options").map(parse_optics_options),
125        otn_options: child_block(line, "otn-options").map(parse_otn_options),
126        link_degrade_monitor: child_block(line, "link-degrade-monitor").map(parse_link_degrade_monitor),
127        esi: parse_esi(line),
128        units: named_children(line, "unit")
129            .map(|(number, unit)| parse_unit(number, unit))
130            .collect(),
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use asterust::config::juniper;
138
139    // Not from documentation: covers statements the Juniper examples do not use. See the README "Sources".
140    const CONFIG: &str = r#"
141interfaces {
142    ge-0/0/0 {
143        description "to p1";
144        unit 0 {
145            description "core link";
146            family inet {
147                address 10.0.1.1/30;
148                address 10.0.2.1/30 {
149                    primary;
150                }
151            }
152            family inet6 {
153                address 2001:db8:1::1/64;
154            }
155            family iso;
156            family mpls;
157        }
158    }
159    ge-0/0/1 {
160        disable;
161        vlan-tagging;
162        unit 100 {
163            vlan-id 100;
164            family inet {
165                address 192.0.2.1/24;
166            }
167        }
168    }
169    inactive: ge-0/0/2 {
170        unit 0;
171    }
172    lo0 {
173        unit 0 {
174            family inet {
175                address 10.255.0.1/32;
176            }
177            family iso {
178                address 49.0001.0100.2550.0001.00;
179            }
180        }
181    }
182    apply-groups GLOBAL;
183}
184"#;
185
186    #[test]
187    fn extracts_units_families_and_addresses() {
188        let ifaces = interfaces(&juniper::parse_braces(CONFIG));
189        let names: Vec<_> = ifaces.iter().map(|i| i.name.as_str()).collect();
190        assert_eq!(names, ["ge-0/0/0", "ge-0/0/1", "lo0"]);
191
192        let core = &ifaces[0];
193        assert_eq!(core.description.as_deref(), Some("to p1"));
194        assert!(!core.disabled);
195        let unit = &core.units[0];
196        assert_eq!(unit.number, "0");
197        assert_eq!(unit.description.as_deref(), Some("core link"));
198        assert_eq!(unit.families, ["inet", "inet6", "iso", "mpls"]);
199        assert_eq!(unit.inet_addresses, ["10.0.1.1/30", "10.0.2.1/30"]);
200        assert_eq!(unit.inet6_addresses, ["2001:db8:1::1/64"]);
201        assert!(unit.iso_addresses.is_empty());
202    }
203
204    #[test]
205    fn disabled_vlan_units_and_loopback_net() {
206        let ifaces = interfaces(&juniper::parse_braces(CONFIG));
207        assert!(ifaces[1].disabled);
208        assert_eq!(ifaces[1].units[0].number, "100");
209        assert_eq!(ifaces[1].units[0].vlan_id, Some(100));
210        assert_eq!(ifaces[2].units[0].iso_addresses, ["49.0001.0100.2550.0001.00"]);
211    }
212
213    #[test]
214    fn missing_interfaces_block_is_empty() {
215        assert!(interfaces(&juniper::parse_braces("system {\n host-name r1;\n}\n")).is_empty());
216    }
217
218    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
219    #[test]
220    fn extracts_physical_interface_settings() {
221        let ifaces = interfaces(&juniper::parse_braces(
222            r#"
223interfaces {
224    xe-0/0/0 {
225        mtu 9192;
226        speed 10g;
227        encapsulation flexible-ethernet-services;
228        vlan-tagging;
229        flexible-vlan-tagging;
230        native-vlan-id 10;
231        per-unit-scheduler;
232        no-gratuitous-arp-request;
233    }
234    inactive: xe-0/0/1 {
235        mtu 1500;
236    }
237    xe-0/0/2 {
238        inactive: mtu 1500;
239    }
240}
241"#,
242        ));
243        assert_eq!(ifaces.len(), 2);
244
245        let xe0 = &ifaces[0];
246        assert_eq!(xe0.mtu.as_deref(), Some("9192"));
247        assert_eq!(xe0.speed.as_deref(), Some("10g"));
248        assert_eq!(xe0.encapsulation.as_deref(), Some("flexible-ethernet-services"));
249        assert!(xe0.vlan_tagging);
250        assert!(xe0.flexible_vlan_tagging);
251        assert_eq!(xe0.native_vlan_id.as_deref(), Some("10"));
252        assert!(xe0.per_unit_scheduler);
253        assert!(xe0.no_gratuitous_arp_request);
254
255        assert_eq!(ifaces[1].mtu, None);
256    }
257
258    #[test]
259    fn physical_interface_settings_default_to_off() {
260        let ifaces = interfaces(&juniper::parse_braces(
261            "interfaces {\n    ge-0/0/0 {\n        disable;\n    }\n}\n",
262        ));
263        let ge = &ifaces[0];
264        assert_eq!(ge.mtu, None);
265        assert_eq!(ge.speed, None);
266        assert_eq!(ge.encapsulation, None);
267        assert!(!ge.vlan_tagging);
268        assert!(!ge.flexible_vlan_tagging);
269        assert_eq!(ge.native_vlan_id, None);
270        assert!(!ge.per_unit_scheduler);
271        assert!(!ge.no_gratuitous_arp_request);
272    }
273
274    // The DOC_* fixtures are adapted from Juniper's BGP User Guide, "BGP Peering Sessions"; see the README "Sources".
275
276    // "Example: Configuring External BGP Point-to-Point Peer Sessions", Device E `show interfaces` (two of four interfaces).
277    const DOC_POINT_TO_POINT: &str = r#"
278interfaces {
279    ge-1/2/0 {
280        unit 0 {
281            description to-A;
282            family inet {
283                address 10.10.10.1/30;
284            }
285        }
286    }
287    ge-0/0/1 {
288        unit 5 {
289            description to-B;
290            family inet {
291                address 10.10.10.5/30;
292            }
293        }
294    }
295}
296"#;
297
298    // "Example: Configure Multiple Single-Hop EBGP Sessions on Different Links Using the Same IPv6 Link-Local
299    // Address", R1 `show interfaces`.
300    const DOC_LINK_LOCAL: &str = r#"
301interfaces {
302    ge-0/0/1 {
303        description R1-to-R2-Link;
304        vlan-tagging;
305        unit 1 {
306            vlan-id 1;
307            family inet6 {
308                address fe80::10/64;
309            }
310        }
311        unit 2 {
312            vlan-id 2;
313            family inet6 {
314                address fe80::10/64;
315            }
316        }
317    }
318    lo0 {
319        unit 0 {
320            family inet {
321                address 198.51.100.1/24 {
322                    primary;
323                }
324            }
325        }
326    }
327}
328"#;
329
330    #[test]
331    fn doc_point_to_point_interfaces() {
332        let ifaces = interfaces(&juniper::parse_braces(DOC_POINT_TO_POINT));
333        let names: Vec<_> = ifaces.iter().map(|i| i.name.as_str()).collect();
334        assert_eq!(names, ["ge-1/2/0", "ge-0/0/1"]);
335        assert_eq!(ifaces[0].units[0].number, "0");
336        assert_eq!(ifaces[0].units[0].description.as_deref(), Some("to-A"));
337        assert_eq!(ifaces[0].units[0].inet_addresses, ["10.10.10.1/30"]);
338        assert_eq!(ifaces[1].units[0].number, "5");
339        assert_eq!(ifaces[1].units[0].inet_addresses, ["10.10.10.5/30"]);
340    }
341
342    #[test]
343    fn doc_link_local_units_vlans_and_primary_address() {
344        let ifaces = interfaces(&juniper::parse_braces(DOC_LINK_LOCAL));
345        let ge = &ifaces[0];
346        assert_eq!(ge.description.as_deref(), Some("R1-to-R2-Link"));
347        assert_eq!(ge.units.len(), 2);
348        assert_eq!(ge.units[0].vlan_id, Some(1));
349        assert_eq!(ge.units[1].vlan_id, Some(2));
350        assert_eq!(ge.units[0].inet6_addresses, ["fe80::10/64"]);
351
352        let lo0 = &ifaces[1];
353        assert_eq!(lo0.units[0].inet_addresses, ["198.51.100.1/24"]);
354    }
355}