Skip to main content

asterust_junos/class_of_service/
interface.rs

1//! `interfaces`
2//! `class-of-service { interfaces { <interface> { ... } interface-set <name> { ... } } }`.
3//!
4//! The `rewrite-value`, `monitoring-profile` and ACX `*-classifier` and `*-rewrite` statements are not extracted.
5//!
6//! # See also
7//!
8//! - [interfaces (class-of-service)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/interfaces-edit-cos.html)
9//! - [unit (class-of-service)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/unit-edit-cos.html)
10//! - [interface-set (class-of-service)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/interface-set-edit-cos.html)
11//! - [Example: Configure and Apply Custom BA Classifiers](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cos-security-devices/cos/topics/example/cos-behavior-aggregate-classifier-configuring-security.html)
12//! - [Example: Controlling Remaining Traffic](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cos-security-devices/topics/example/cos-control-remaining-traffic-security-configuring.html)
13//! - [Example: Configuring a Four-Level Scheduler Hierarchy](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cos-security-devices/topics/example/cos-hierarchical-scheduler-security-configuring.html)
14
15use super::platform::parse_multi_destination;
16use super::scheduler::{rate_of, SchedulerRate};
17use super::words;
18use crate::{active_children, arg_of, child_block, has_leaf, named_children, value_after};
19use asterust::config::ConfigLine;
20
21/// A classifier or rewrite rule applied to an interface or unit, such as `dscp ba-classifier;`,
22/// `ieee-802.1 dot1p vlan-tag outer;` or `exp mpls-out protocol mpls-any;`.
23#[derive(Clone, Debug, PartialEq, Eq)]
24#[non_exhaustive]
25pub struct AppliedMapping {
26    /// `dscp`, `dscp-ipv6`, `exp`, `exp-push-push-push`, `exp-swap-push-push`, `ieee-802.1`, `inet-precedence`, ...
27    pub kind: String,
28    /// The name of the classifier or rewrite rule, or `default`.
29    pub name: String,
30    /// `mpls`, `inet` or `all`.
31    pub family: Option<String>,
32    pub protocol: Option<String>,
33    pub vlan_tag: Option<String>,
34}
35
36/// A traffic-control profile applied with `output-traffic-control-profile <name> [shared-instance <name>]`.
37#[derive(Clone, Debug, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct AppliedProfile {
40    pub name: String,
41    pub shared_instance: Option<String>,
42}
43
44/// The statements that an interface and a logical unit have in common.
45#[derive(Clone, Debug, Default, PartialEq, Eq)]
46#[non_exhaustive]
47pub struct CosSettings {
48    pub classifiers: Vec<AppliedMapping>,
49    pub rewrite_rules: Vec<AppliedMapping>,
50    pub forwarding_class: Option<String>,
51    pub fragmentation_map: Option<String>,
52    pub scheduler_map: Option<String>,
53    pub scheduler_map_chassis: Option<String>,
54    pub input_scheduler_map: Option<String>,
55    pub shaping_rate: Option<SchedulerRate>,
56    pub input_shaping_rate: Option<SchedulerRate>,
57    pub input_traffic_control_profile: Option<AppliedProfile>,
58    pub input_traffic_control_profile_remaining: Option<AppliedProfile>,
59    pub output_traffic_control_profile: Option<AppliedProfile>,
60    pub output_traffic_control_profile_remaining: Option<AppliedProfile>,
61    pub per_session_scheduler: bool,
62    pub policy_map: Option<String>,
63    pub policy_map_marking: bool,
64    pub hierarchical_scheduler: bool,
65    /// `replicate` or `scale`.
66    pub member_link_scheduler: Option<String>,
67    pub congestion_notification_profile: Option<String>,
68    pub dedicated_buffer_profile: Option<String>,
69    pub virtual_channel_group: Option<String>,
70    pub dynamic_threshold_profile: Option<String>,
71    /// `drop-congestion-notification`: generate DCN-trimmed packets in case of congestion.
72    pub drop_congestion_notification: bool,
73    /// The `classifiers` of `multi-destination`.
74    pub multi_destination_classifiers: Vec<AppliedMapping>,
75}
76
77/// A `unit <number>` of a class-of-service interface.
78#[derive(Clone, Debug, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct CosUnit {
81    pub number: String,
82    pub settings: CosSettings,
83}
84
85/// A `forwarding-class-set <name>` or `slice <name>` of an interface, with its traffic-control profile.
86#[derive(Clone, Debug, PartialEq, Eq)]
87#[non_exhaustive]
88pub struct CosBinding {
89    pub name: String,
90    pub output_traffic_control_profile: Option<AppliedProfile>,
91}
92
93/// An interface of `class-of-service interfaces`.
94#[derive(Clone, Debug, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct CosInterface {
97    pub name: String,
98    pub settings: CosSettings,
99    pub forwarding_class_sets: Vec<CosBinding>,
100    pub slices: Vec<CosBinding>,
101    pub units: Vec<CosUnit>,
102}
103
104/// An `interface-set <name>` of `class-of-service interfaces`.
105#[derive(Clone, Debug, PartialEq, Eq)]
106#[non_exhaustive]
107pub struct CosInterfaceSet {
108    pub name: String,
109    /// `proportional <value>` or `equal`.
110    pub excess_bandwidth_share: Option<String>,
111    pub internal_node: bool,
112    pub output_traffic_control_profile: Option<AppliedProfile>,
113    pub output_traffic_control_profile_remaining: Option<AppliedProfile>,
114}
115
116pub(super) fn parse_mappings(line: &ConfigLine, block: &str) -> Vec<AppliedMapping> {
117    let Some(block) = child_block(line, block) else {
118        return Vec::new();
119    };
120    active_children(block)
121        .filter_map(|statement| {
122            let words = words(statement, 0);
123            let (kind, name) = (words.first()?, words.get(1)?);
124            Some(AppliedMapping {
125                kind: kind.to_string(),
126                name: name.to_string(),
127                family: value_after(&words, "family"),
128                protocol: value_after(&words, "protocol"),
129                vlan_tag: value_after(&words, "vlan-tag"),
130            })
131        })
132        .collect()
133}
134
135fn parse_profile(line: &ConfigLine, keyword: &str) -> Option<AppliedProfile> {
136    let words: Vec<&str> = arg_of(line, keyword)?.split_whitespace().collect();
137    Some(AppliedProfile {
138        name: words.first()?.to_string(),
139        shared_instance: value_after(&words, "shared-instance"),
140    })
141}
142
143fn parse_settings(line: &ConfigLine) -> CosSettings {
144    let field = |keyword: &str| arg_of(line, keyword).map(str::to_string);
145    CosSettings {
146        classifiers: parse_mappings(line, "classifiers"),
147        rewrite_rules: parse_mappings(line, "rewrite-rules"),
148        forwarding_class: field("forwarding-class"),
149        fragmentation_map: field("fragmentation-map"),
150        scheduler_map: field("scheduler-map"),
151        scheduler_map_chassis: field("scheduler-map-chassis"),
152        input_scheduler_map: field("input-scheduler-map"),
153        shaping_rate: rate_of(line, "shaping-rate"),
154        input_shaping_rate: rate_of(line, "input-shaping-rate"),
155        input_traffic_control_profile: parse_profile(line, "input-traffic-control-profile"),
156        input_traffic_control_profile_remaining: parse_profile(line, "input-traffic-control-profile-remaining"),
157        output_traffic_control_profile: parse_profile(line, "output-traffic-control-profile"),
158        output_traffic_control_profile_remaining: parse_profile(line, "output-traffic-control-profile-remaining"),
159        per_session_scheduler: has_leaf(line, "per-session-scheduler"),
160        policy_map: field("policy-map"),
161        policy_map_marking: has_leaf(line, "policy-map-marking"),
162        hierarchical_scheduler: has_leaf(line, "hierarchical-scheduler"),
163        member_link_scheduler: field("member-link-scheduler"),
164        congestion_notification_profile: field("congestion-notification-profile"),
165        dedicated_buffer_profile: field("dedicated-buffer-profile"),
166        virtual_channel_group: field("virtual-channel-group"),
167        dynamic_threshold_profile: field("dynamic-threshold-profile"),
168        drop_congestion_notification: has_leaf(line, "drop-congestion-notification"),
169        multi_destination_classifiers: parse_multi_destination(line),
170    }
171}
172
173fn parse_bindings(interface: &ConfigLine, keyword: &str) -> Vec<CosBinding> {
174    named_children(interface, keyword)
175        .map(|(name, binding)| CosBinding {
176            name: name.to_string(),
177            output_traffic_control_profile: parse_profile(binding, "output-traffic-control-profile"),
178        })
179        .collect()
180}
181
182fn parse_interface(name: &str, interface: &ConfigLine) -> CosInterface {
183    CosInterface {
184        name: name.to_string(),
185        settings: parse_settings(interface),
186        forwarding_class_sets: parse_bindings(interface, "forwarding-class-set"),
187        slices: parse_bindings(interface, "slice"),
188        units: named_children(interface, "unit")
189            .map(|(number, unit)| CosUnit {
190                number: number.to_string(),
191                settings: parse_settings(unit),
192            })
193            .collect(),
194    }
195}
196
197fn parse_interface_set(name: &str, set: &ConfigLine) -> CosInterfaceSet {
198    let share = crate::statement_words(set, "excess-bandwidth-share").map(|words| words.join(" "));
199    CosInterfaceSet {
200        name: name.to_string(),
201        excess_bandwidth_share: share,
202        internal_node: has_leaf(set, "internal-node"),
203        output_traffic_control_profile: parse_profile(set, "output-traffic-control-profile"),
204        output_traffic_control_profile_remaining: parse_profile(set, "output-traffic-control-profile-remaining"),
205    }
206}
207
208pub(super) fn parse_interfaces(cos: &ConfigLine) -> (Vec<CosInterface>, Vec<CosInterfaceSet>) {
209    let Some(block) = child_block(cos, "interfaces") else {
210        return (Vec::new(), Vec::new());
211    };
212    let mut interfaces = Vec::new();
213    let mut sets = Vec::new();
214    for child in active_children(block) {
215        if let Some(name) = child.arg("interface-set") {
216            sets.push(parse_interface_set(
217                name.split_whitespace().next().unwrap_or(name),
218                child,
219            ));
220        } else if let Some(name) = child.text.split_whitespace().next() {
221            interfaces.push(parse_interface(name, child));
222        }
223    }
224    (interfaces, sets)
225}
226
227#[cfg(test)]
228mod tests {
229    use crate::class_of_service::class_of_service;
230    use asterust::config::juniper;
231
232    // The `class-of-service interfaces` of the BA classifier, IPv6 rewrite rule, scheduler map, hierarchical scheduler
233    // and remaining traffic examples (Class of Service User Guide for Security Devices), wrapped in `class-of-service`
234    // and shortened; see the README "Sources".
235    const DOC_UNITS: &str = r#"
236class-of-service {
237    interfaces {
238        ge-0/0/0 {
239            unit 0 {
240                classifiers {
241                    dscp ba-classifier;
242                }
243                rewrite-rules {
244                    dscp-ipv6 rewrite-ipv6-dscps;
245                }
246                scheduler-map diffserv-cos-map;
247            }
248        }
249        ge-0/0/1 {
250            scheduler-map be-map;
251        }
252    }
253}
254"#;
255
256    const DOC_HIERARCHY: &str = r#"
257class-of-service {
258    interfaces {
259        ge-1/0/0 {
260            output-traffic-control-profile tcp-500m-shaping-rate;
261            unit 0 {
262                output-traffic-control-profile tcp-cvlan0;
263            }
264            unit 1 {
265                output-traffic-control-profile tcp-cvlan1;
266            }
267        }
268        interface-set svlan0 {
269            output-traffic-control-profile tcp-svlan0;
270        }
271        interface-set svlan1 {
272            output-traffic-control-profile tcp-svlan1;
273            output-traffic-control-profile-remaining tcp-svlan1-remaining;
274        }
275    }
276}
277"#;
278
279    // Not from documentation: written from the CLI Reference. See the README "Sources".
280    const EXTRA: &str = r#"
281class-of-service {
282    interfaces {
283        xe-0/0/0 {
284            hierarchical-scheduler;
285            shaping-rate 5g burst-size 128k;
286            input-shaping-rate percent 50;
287            input-scheduler-map in-map;
288            forwarding-class-set VOICE {
289                output-traffic-control-profile tcp-voice;
290            }
291            slice A {
292                output-traffic-control-profile tcp-a shared-instance si1;
293            }
294            member-link-scheduler scale;
295            congestion-notification-profile cnp1;
296            dedicated-buffer-profile dbp1;
297            classifiers {
298                ieee-802.1 dot1p vlan-tag outer;
299            }
300            rewrite-rules {
301                exp mpls-out protocol mpls-any;
302                exp-push-push-push default;
303            }
304            unit 100 {
305                forwarding-class be;
306                fragmentation-map fm1;
307                input-traffic-control-profile tcp-in shared-instance in1;
308                per-session-scheduler;
309                policy-map pm1;
310                policy-map-marking;
311                classifiers {
312                    dscp default family mpls;
313                }
314            }
315        }
316        interface-set EDGE {
317            excess-bandwidth-share proportional 100;
318            internal-node;
319        }
320        interface-set SPLIT {
321            excess-bandwidth-share equal;
322        }
323    }
324}
325"#;
326
327    fn cos(text: &str) -> crate::class_of_service::ClassOfService {
328        class_of_service(&juniper::parse_braces(text)).unwrap()
329    }
330
331    #[test]
332    fn reads_the_guide_units() {
333        let cos = cos(DOC_UNITS);
334        assert_eq!(cos.interfaces.len(), 2);
335        let first = &cos.interfaces[0];
336        assert_eq!(first.name, "ge-0/0/0");
337        assert_eq!(first.units.len(), 1);
338        let unit = &first.units[0];
339        assert_eq!(unit.number, "0");
340        assert_eq!(unit.settings.classifiers[0].kind, "dscp");
341        assert_eq!(unit.settings.classifiers[0].name, "ba-classifier");
342        assert_eq!(unit.settings.rewrite_rules[0].kind, "dscp-ipv6");
343        assert_eq!(unit.settings.rewrite_rules[0].name, "rewrite-ipv6-dscps");
344        assert_eq!(unit.settings.scheduler_map.as_deref(), Some("diffserv-cos-map"));
345        assert_eq!(cos.interfaces[1].settings.scheduler_map.as_deref(), Some("be-map"));
346        assert!(cos.interfaces[1].units.is_empty());
347    }
348
349    #[test]
350    fn reads_the_guide_hierarchy() {
351        let cos = cos(DOC_HIERARCHY);
352        assert_eq!(cos.interfaces.len(), 1);
353        let port = &cos.interfaces[0];
354        let profile = port.settings.output_traffic_control_profile.as_ref().unwrap();
355        assert_eq!(profile.name, "tcp-500m-shaping-rate");
356        assert_eq!(profile.shared_instance, None);
357        assert_eq!(port.units.len(), 2);
358        assert_eq!(
359            port.units[1]
360                .settings
361                .output_traffic_control_profile
362                .as_ref()
363                .unwrap()
364                .name,
365            "tcp-cvlan1"
366        );
367        assert_eq!(cos.interface_sets.len(), 2);
368        assert_eq!(cos.interface_sets[0].name, "svlan0");
369        assert_eq!(
370            cos.interface_sets[0]
371                .output_traffic_control_profile
372                .as_ref()
373                .unwrap()
374                .name,
375            "tcp-svlan0"
376        );
377        assert_eq!(cos.interface_sets[0].output_traffic_control_profile_remaining, None);
378        assert_eq!(
379            cos.interface_sets[1]
380                .output_traffic_control_profile_remaining
381                .as_ref()
382                .unwrap()
383                .name,
384            "tcp-svlan1-remaining"
385        );
386    }
387
388    #[test]
389    fn reads_the_interface_options() {
390        let interface = &cos(EXTRA).interfaces[0];
391        let settings = &interface.settings;
392        assert!(settings.hierarchical_scheduler);
393        let shaping = settings.shaping_rate.as_ref().unwrap();
394        assert_eq!(shaping.value.as_deref(), Some("5g"));
395        assert_eq!(shaping.burst_size.as_deref(), Some("128k"));
396        let input = settings.input_shaping_rate.as_ref().unwrap();
397        assert_eq!(input.mode.as_deref(), Some("percent"));
398        assert_eq!(settings.input_scheduler_map.as_deref(), Some("in-map"));
399        assert_eq!(settings.member_link_scheduler.as_deref(), Some("scale"));
400        assert_eq!(settings.congestion_notification_profile.as_deref(), Some("cnp1"));
401        assert_eq!(settings.dedicated_buffer_profile.as_deref(), Some("dbp1"));
402        assert_eq!(interface.forwarding_class_sets[0].name, "VOICE");
403        assert_eq!(
404            interface.forwarding_class_sets[0]
405                .output_traffic_control_profile
406                .as_ref()
407                .unwrap()
408                .name,
409            "tcp-voice"
410        );
411        let slice = interface.slices[0].output_traffic_control_profile.as_ref().unwrap();
412        assert_eq!(slice.name, "tcp-a");
413        assert_eq!(slice.shared_instance.as_deref(), Some("si1"));
414    }
415
416    #[test]
417    fn reads_vlan_tags_protocols_and_families() {
418        let interface = &cos(EXTRA).interfaces[0];
419        let classifier = &interface.settings.classifiers[0];
420        assert_eq!(classifier.kind, "ieee-802.1");
421        assert_eq!(classifier.vlan_tag.as_deref(), Some("outer"));
422        assert_eq!(
423            interface.settings.rewrite_rules[0].protocol.as_deref(),
424            Some("mpls-any")
425        );
426        assert_eq!(interface.settings.rewrite_rules[1].kind, "exp-push-push-push");
427        assert_eq!(interface.settings.rewrite_rules[1].name, "default");
428        let unit = &interface.units[0];
429        assert_eq!(unit.settings.classifiers[0].name, "default");
430        assert_eq!(unit.settings.classifiers[0].family.as_deref(), Some("mpls"));
431    }
432
433    #[test]
434    fn reads_the_unit_options() {
435        let unit = &cos(EXTRA).interfaces[0].units[0];
436        assert_eq!(unit.number, "100");
437        assert_eq!(unit.settings.forwarding_class.as_deref(), Some("be"));
438        assert_eq!(unit.settings.fragmentation_map.as_deref(), Some("fm1"));
439        let profile = unit.settings.input_traffic_control_profile.as_ref().unwrap();
440        assert_eq!(profile.name, "tcp-in");
441        assert_eq!(profile.shared_instance.as_deref(), Some("in1"));
442        assert!(unit.settings.per_session_scheduler);
443        assert_eq!(unit.settings.policy_map.as_deref(), Some("pm1"));
444        assert!(unit.settings.policy_map_marking);
445        assert!(!unit.settings.hierarchical_scheduler);
446    }
447
448    #[test]
449    fn reads_the_interface_set_options() {
450        let sets = cos(EXTRA).interface_sets;
451        assert_eq!(sets.len(), 2);
452        assert_eq!(sets[0].name, "EDGE");
453        assert_eq!(sets[0].excess_bandwidth_share.as_deref(), Some("proportional 100"));
454        assert!(sets[0].internal_node);
455        assert_eq!(sets[1].excess_bandwidth_share.as_deref(), Some("equal"));
456        assert!(!sets[1].internal_node);
457    }
458}