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, McAe, McAeEvents};
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, VirtualGatewayEsi, VlanMap,
39    VlanTags, VrrpGroup, 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    /// `"copper"` or `"fiber"`, for a dual-purpose uplink port.
68    pub media_type: Option<String>,
69    pub vlan_tagging: bool,
70    pub flexible_vlan_tagging: bool,
71    pub native_vlan_id: Option<String>,
72    pub per_unit_scheduler: bool,
73    pub no_gratuitous_arp_request: bool,
74    pub hold_time: Option<HoldTime>,
75    pub ether_options: Option<EtherOptions>,
76    pub aggregated_ether_options: Option<AggregatedEtherOptions>,
77    pub auto_configure: Option<AutoConfigure>,
78    pub optics_options: Option<OpticsOptions>,
79    pub otn_options: Option<OtnOptions>,
80    pub link_degrade_monitor: Option<LinkDegradeMonitor>,
81    pub esi: Option<Esi>,
82    pub units: Vec<InterfaceUnit>,
83}
84
85/// Returns every interface under the top-level `interfaces` block.
86///
87/// # Examples
88///
89/// ```
90/// use asterust::config::juniper;
91/// use asterust_junos::interfaces::interfaces;
92///
93/// let config = juniper::parse_braces("interfaces {\n    ge-0/0/0 {\n        mtu 9192;\n    }\n}\n");
94/// let found = interfaces(&config);
95/// assert_eq!(found[0].name, "ge-0/0/0");
96/// assert_eq!(found[0].mtu.as_deref(), Some("9192"));
97/// ```
98pub fn interfaces(config: &Config) -> Vec<Interface> {
99    let Some(root) = top_level(config, "interfaces") else {
100        return Vec::new();
101    };
102    // Interface names have no spaces; this skips `apply-groups`, `interface-range <x>` and similar.
103    active_children(root)
104        .filter(|c| !c.text.contains(' '))
105        .map(parse_interface)
106        .collect()
107}
108
109fn parse_interface(line: &ConfigLine) -> Interface {
110    Interface {
111        name: line.text.clone(),
112        description: arg_of(line, "description").map(str::to_string),
113        disabled: has_leaf(line, "disable"),
114        mtu: arg_of(line, "mtu").map(str::to_string),
115        speed: arg_of(line, "speed").map(str::to_string),
116        encapsulation: arg_of(line, "encapsulation").map(str::to_string),
117        media_type: arg_of(line, "media-type").map(str::to_string),
118        vlan_tagging: has_leaf(line, "vlan-tagging"),
119        flexible_vlan_tagging: has_leaf(line, "flexible-vlan-tagging"),
120        native_vlan_id: arg_of(line, "native-vlan-id").map(str::to_string),
121        per_unit_scheduler: has_leaf(line, "per-unit-scheduler"),
122        no_gratuitous_arp_request: has_leaf(line, "no-gratuitous-arp-request"),
123        hold_time: parse_hold_time(line),
124        ether_options: parse_ether_options(line),
125        aggregated_ether_options: child_block(line, "aggregated-ether-options").map(parse_aggregated_ether_options),
126        auto_configure: child_block(line, "auto-configure").map(parse_auto_configure),
127        optics_options: child_block(line, "optics-options").map(parse_optics_options),
128        otn_options: child_block(line, "otn-options").map(parse_otn_options),
129        link_degrade_monitor: child_block(line, "link-degrade-monitor").map(parse_link_degrade_monitor),
130        esi: parse_esi(line),
131        units: named_children(line, "unit")
132            .map(|(number, unit)| parse_unit(number, unit))
133            .collect(),
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    use asterust::config::juniper;
141
142    // Not from documentation: covers statements the Juniper examples do not use. See the README "Sources".
143    const CONFIG: &str = r#"
144interfaces {
145    ge-0/0/0 {
146        description "to p1";
147        unit 0 {
148            description "core link";
149            family inet {
150                address 10.0.1.1/30;
151                address 10.0.2.1/30 {
152                    primary;
153                }
154            }
155            family inet6 {
156                address 2001:db8:1::1/64;
157            }
158            family iso;
159            family mpls;
160        }
161    }
162    ge-0/0/1 {
163        disable;
164        vlan-tagging;
165        unit 100 {
166            vlan-id 100;
167            family inet {
168                address 192.0.2.1/24;
169            }
170        }
171    }
172    inactive: ge-0/0/2 {
173        unit 0;
174    }
175    lo0 {
176        unit 0 {
177            family inet {
178                address 10.255.0.1/32;
179            }
180            family iso {
181                address 49.0001.0100.2550.0001.00;
182            }
183        }
184    }
185    apply-groups GLOBAL;
186}
187"#;
188
189    #[test]
190    fn extracts_units_families_and_addresses() {
191        let ifaces = interfaces(&juniper::parse_braces(CONFIG));
192        let names: Vec<_> = ifaces.iter().map(|i| i.name.as_str()).collect();
193        assert_eq!(names, ["ge-0/0/0", "ge-0/0/1", "lo0"]);
194
195        let core = &ifaces[0];
196        assert_eq!(core.description.as_deref(), Some("to p1"));
197        assert!(!core.disabled);
198        let unit = &core.units[0];
199        assert_eq!(unit.number, "0");
200        assert_eq!(unit.description.as_deref(), Some("core link"));
201        assert_eq!(unit.families, ["inet", "inet6", "iso", "mpls"]);
202        assert_eq!(unit.inet_addresses, ["10.0.1.1/30", "10.0.2.1/30"]);
203        assert_eq!(unit.inet6_addresses, ["2001:db8:1::1/64"]);
204        assert!(unit.iso_addresses.is_empty());
205    }
206
207    #[test]
208    fn disabled_vlan_units_and_loopback_net() {
209        let ifaces = interfaces(&juniper::parse_braces(CONFIG));
210        assert!(ifaces[1].disabled);
211        assert_eq!(ifaces[1].units[0].number, "100");
212        assert_eq!(ifaces[1].units[0].vlan_id, Some(100));
213        assert_eq!(ifaces[2].units[0].iso_addresses, ["49.0001.0100.2550.0001.00"]);
214    }
215
216    #[test]
217    fn missing_interfaces_block_is_empty() {
218        assert!(interfaces(&juniper::parse_braces("system {\n host-name r1;\n}\n")).is_empty());
219    }
220
221    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
222    #[test]
223    fn extracts_physical_interface_settings() {
224        let ifaces = interfaces(&juniper::parse_braces(
225            r#"
226interfaces {
227    xe-0/0/0 {
228        mtu 9192;
229        speed 10g;
230        encapsulation flexible-ethernet-services;
231        vlan-tagging;
232        flexible-vlan-tagging;
233        native-vlan-id 10;
234        per-unit-scheduler;
235        no-gratuitous-arp-request;
236    }
237    inactive: xe-0/0/1 {
238        mtu 1500;
239    }
240    xe-0/0/2 {
241        inactive: mtu 1500;
242    }
243}
244"#,
245        ));
246        assert_eq!(ifaces.len(), 2);
247
248        let xe0 = &ifaces[0];
249        assert_eq!(xe0.mtu.as_deref(), Some("9192"));
250        assert_eq!(xe0.speed.as_deref(), Some("10g"));
251        assert_eq!(xe0.encapsulation.as_deref(), Some("flexible-ethernet-services"));
252        assert!(xe0.vlan_tagging);
253        assert!(xe0.flexible_vlan_tagging);
254        assert_eq!(xe0.native_vlan_id.as_deref(), Some("10"));
255        assert!(xe0.per_unit_scheduler);
256        assert!(xe0.no_gratuitous_arp_request);
257
258        assert_eq!(ifaces[1].mtu, None);
259    }
260
261    #[test]
262    fn physical_interface_settings_default_to_off() {
263        let ifaces = interfaces(&juniper::parse_braces(
264            "interfaces {\n    ge-0/0/0 {\n        disable;\n    }\n}\n",
265        ));
266        let ge = &ifaces[0];
267        assert_eq!(ge.mtu, None);
268        assert_eq!(ge.speed, None);
269        assert_eq!(ge.encapsulation, None);
270        assert!(!ge.vlan_tagging);
271        assert!(!ge.flexible_vlan_tagging);
272        assert_eq!(ge.native_vlan_id, None);
273        assert!(!ge.per_unit_scheduler);
274        assert!(!ge.no_gratuitous_arp_request);
275    }
276
277    // The DOC_* fixtures are adapted from Juniper's BGP User Guide, "BGP Peering Sessions"; see the README "Sources".
278
279    // "Example: Configuring External BGP Point-to-Point Peer Sessions", Device E `show interfaces` (two of four interfaces).
280    const DOC_POINT_TO_POINT: &str = r#"
281interfaces {
282    ge-1/2/0 {
283        unit 0 {
284            description to-A;
285            family inet {
286                address 10.10.10.1/30;
287            }
288        }
289    }
290    ge-0/0/1 {
291        unit 5 {
292            description to-B;
293            family inet {
294                address 10.10.10.5/30;
295            }
296        }
297    }
298}
299"#;
300
301    // "Example: Configure Multiple Single-Hop EBGP Sessions on Different Links Using the Same IPv6 Link-Local
302    // Address", R1 `show interfaces`.
303    const DOC_LINK_LOCAL: &str = r#"
304interfaces {
305    ge-0/0/1 {
306        description R1-to-R2-Link;
307        vlan-tagging;
308        unit 1 {
309            vlan-id 1;
310            family inet6 {
311                address fe80::10/64;
312            }
313        }
314        unit 2 {
315            vlan-id 2;
316            family inet6 {
317                address fe80::10/64;
318            }
319        }
320    }
321    lo0 {
322        unit 0 {
323            family inet {
324                address 198.51.100.1/24 {
325                    primary;
326                }
327            }
328        }
329    }
330}
331"#;
332
333    #[test]
334    fn doc_point_to_point_interfaces() {
335        let ifaces = interfaces(&juniper::parse_braces(DOC_POINT_TO_POINT));
336        let names: Vec<_> = ifaces.iter().map(|i| i.name.as_str()).collect();
337        assert_eq!(names, ["ge-1/2/0", "ge-0/0/1"]);
338        assert_eq!(ifaces[0].units[0].number, "0");
339        assert_eq!(ifaces[0].units[0].description.as_deref(), Some("to-A"));
340        assert_eq!(ifaces[0].units[0].inet_addresses, ["10.10.10.1/30"]);
341        assert_eq!(ifaces[1].units[0].number, "5");
342        assert_eq!(ifaces[1].units[0].inet_addresses, ["10.10.10.5/30"]);
343    }
344
345    #[test]
346    fn doc_link_local_units_vlans_and_primary_address() {
347        let ifaces = interfaces(&juniper::parse_braces(DOC_LINK_LOCAL));
348        let ge = &ifaces[0];
349        assert_eq!(ge.description.as_deref(), Some("R1-to-R2-Link"));
350        assert_eq!(ge.units.len(), 2);
351        assert_eq!(ge.units[0].vlan_id, Some(1));
352        assert_eq!(ge.units[1].vlan_id, Some(2));
353        assert_eq!(ge.units[0].inet6_addresses, ["fe80::10/64"]);
354
355        let lo0 = &ifaces[1];
356        assert_eq!(lo0.units[0].inet_addresses, ["198.51.100.1/24"]);
357    }
358}