asterust-junos 0.5.5

Typed Juniper JunOS config views (interfaces, protocols, routing instances and options, policy options, firewall filters, class of service, system, services) extracted from an asterust config tree.
Documentation
//! `traffic-control-profiles`
//! `class-of-service { traffic-control-profiles { <name> { ... } } }`.
//!
//! # See also
//!
//! - [traffic-control-profiles](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/traffic-control-profiles-edit-cos.html)
//! - [guaranteed-rate](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/guaranteed-rate-edit-cos.html)
//! - [delay-buffer-rate](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/delay-buffer-rate-edit-cos.html)
//! - [overhead-accounting](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/overhead-accounting-edit-cos.html)
//! - [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)
//! - [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)

use super::scheduler::{parse_rate, rate_of, SchedulerRate};
use super::words;
use crate::{active_children, arg_of, child_block, has_leaf, statement_words, value_after};
use asterust::config::ConfigLine;

/// An `overhead-accounting <mode> [bytes <n>]` statement.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct OverheadAccounting {
    /// `frame-mode`, `cell-mode`, `frame-mode-bytes` or `cell-mode-bytes`.
    pub mode: String,
    pub bytes: Option<String>,
}

/// A per-priority `shaping-rate-*` or `excess-rate-*` statement of a traffic-control profile.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ProfileRate {
    /// The statement, such as `shaping-rate-priority-high` or `excess-rate-low`.
    pub statement: String,
    pub rate: SchedulerRate,
}

/// A `traffic-control-profiles` entry.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct TrafficControlProfile {
    pub name: String,
    pub shaping_rate: Option<SchedulerRate>,
    pub guaranteed_rate: Option<SchedulerRate>,
    pub delay_buffer_rate: Option<SchedulerRate>,
    pub excess_rate: Option<SchedulerRate>,
    /// The `shaping-rate-excess-*`, `shaping-rate-priority-*` and `excess-rate-*` statements, in the order written.
    pub priority_rates: Vec<ProfileRate>,
    pub scheduler_map: Option<String>,
    pub overhead_accounting: Option<OverheadAccounting>,
    pub adjust_minimum: Option<String>,
    pub atm_service: Option<String>,
    pub max_burst_size: Option<String>,
    pub peak_rate: Option<String>,
    pub sustained_rate: Option<String>,
    pub granularity_mode_low: bool,
    pub queue_mode_4q: bool,
    pub strict_priority_scheduler: bool,
}

fn parse_profile(profile: &ConfigLine) -> Option<TrafficControlProfile> {
    let name = profile.text.split_whitespace().next()?;
    let field = |keyword: &str| arg_of(profile, keyword).map(str::to_string);
    Some(TrafficControlProfile {
        name: name.to_string(),
        shaping_rate: rate_of(profile, "shaping-rate"),
        guaranteed_rate: rate_of(profile, "guaranteed-rate"),
        delay_buffer_rate: rate_of(profile, "delay-buffer-rate"),
        excess_rate: rate_of(profile, "excess-rate"),
        priority_rates: active_children(profile)
            .filter_map(|child| {
                let statement = child.text.split_whitespace().next()?;
                (statement.starts_with("shaping-rate-") || statement.starts_with("excess-rate-")).then(|| ProfileRate {
                    statement: statement.to_string(),
                    rate: parse_rate(&words(child, 1)),
                })
            })
            .collect(),
        scheduler_map: field("scheduler-map"),
        overhead_accounting: statement_words(profile, "overhead-accounting").and_then(|words| {
            Some(OverheadAccounting {
                mode: words.first()?.to_string(),
                bytes: value_after(&words, "bytes"),
            })
        }),
        adjust_minimum: field("adjust-minimum"),
        atm_service: field("atm-service"),
        max_burst_size: field("max-burst-size"),
        peak_rate: field("peak-rate"),
        sustained_rate: field("sustained-rate"),
        granularity_mode_low: has_leaf(profile, "granularity-mode-low"),
        queue_mode_4q: has_leaf(profile, "queue-mode-4q"),
        strict_priority_scheduler: has_leaf(profile, "strict-priority-scheduler"),
    })
}

pub(super) fn parse_traffic_control_profiles(cos: &ConfigLine) -> Vec<TrafficControlProfile> {
    let Some(block) = child_block(cos, "traffic-control-profiles") else {
        return Vec::new();
    };
    active_children(block).filter_map(parse_profile).collect()
}

#[cfg(test)]
mod tests {
    use crate::class_of_service::class_of_service;
    use asterust::config::juniper;

    // The `traffic-control-profiles` of Example: Configuring a Four-Level Scheduler Hierarchy and Example: Controlling
    // Remaining Traffic (Class of Service User Guide for Security Devices), wrapped in `class-of-service` and
    // shortened; see the README "Sources".
    const DOC_PROFILES: &str = r#"
class-of-service {
    traffic-control-profiles {
        tcp-500m-shaping-rate {
            shaping-rate 500m;
        }
        tcp-svlan0 {
            shaping-rate 200m;
            guaranteed-rate 100m;
            delay-buffer-rate 300m;
        }
        tcp-cvlan0 {
            shaping-rate 100m;
            guaranteed-rate 60m;
            scheduler-map tcp-map-cvlan0;
        }
        tcp-svlan1-remaining {
            shaping-rate 300m;
            guaranteed-rate 200m;
            scheduler-map smap-remainder;
        }
        tcp-ifl1 {
            scheduler-map smap-ifl1;
        }
    }
}
"#;

    // Not from documentation: written from the CLI Reference. See the README "Sources".
    const EXTRA: &str = r#"
class-of-service {
    traffic-control-profiles {
        full {
            shaping-rate percent 80 burst-size 64k;
            guaranteed-rate 10m burst-size 32k;
            excess-rate proportion 20;
            excess-rate-high percent 60;
            excess-rate-low proportion 5;
            shaping-rate-priority-high 50m;
            shaping-rate-excess-low percent 10 burst-size 8k;
            overhead-accounting frame-mode-bytes bytes 20;
            adjust-minimum 1m;
            atm-service cbr;
            max-burst-size 64;
            peak-rate 100m;
            sustained-rate 50m;
            granularity-mode-low;
            queue-mode-4q;
            strict-priority-scheduler;
        }
        plain {
            overhead-accounting cell-mode;
        }
    }
}
"#;

    fn profiles(text: &str) -> Vec<super::TrafficControlProfile> {
        class_of_service(&juniper::parse_braces(text))
            .unwrap()
            .traffic_control_profiles
    }

    #[test]
    fn reads_the_guide_profiles() {
        let profiles = profiles(DOC_PROFILES);
        assert_eq!(profiles.len(), 5);
        assert_eq!(profiles[0].name, "tcp-500m-shaping-rate");
        assert_eq!(
            profiles[0].shaping_rate.as_ref().unwrap().value.as_deref(),
            Some("500m")
        );
        assert_eq!(profiles[0].guaranteed_rate, None);
        let svlan = &profiles[1];
        assert_eq!(svlan.shaping_rate.as_ref().unwrap().value.as_deref(), Some("200m"));
        assert_eq!(svlan.guaranteed_rate.as_ref().unwrap().value.as_deref(), Some("100m"));
        assert_eq!(svlan.delay_buffer_rate.as_ref().unwrap().value.as_deref(), Some("300m"));
        assert_eq!(svlan.scheduler_map, None);
        assert_eq!(profiles[2].scheduler_map.as_deref(), Some("tcp-map-cvlan0"));
        assert_eq!(profiles[3].name, "tcp-svlan1-remaining");
        assert_eq!(profiles[4].name, "tcp-ifl1");
        assert_eq!(profiles[4].scheduler_map.as_deref(), Some("smap-ifl1"));
        assert_eq!(profiles[4].shaping_rate, None);
    }

    #[test]
    fn reads_the_rates() {
        let profile = &profiles(EXTRA)[0];
        let shaping = profile.shaping_rate.as_ref().unwrap();
        assert_eq!(shaping.mode.as_deref(), Some("percent"));
        assert_eq!(shaping.value.as_deref(), Some("80"));
        assert_eq!(shaping.burst_size.as_deref(), Some("64k"));
        let guaranteed = profile.guaranteed_rate.as_ref().unwrap();
        assert_eq!(guaranteed.value.as_deref(), Some("10m"));
        assert_eq!(guaranteed.burst_size.as_deref(), Some("32k"));
        let excess = profile.excess_rate.as_ref().unwrap();
        assert_eq!(excess.mode.as_deref(), Some("proportion"));
        assert_eq!(excess.value.as_deref(), Some("20"));
    }

    #[test]
    fn reads_the_priority_rates_in_order() {
        let rates = &profiles(EXTRA)[0].priority_rates;
        assert_eq!(rates.len(), 4);
        assert_eq!(rates[0].statement, "excess-rate-high");
        assert_eq!(rates[0].rate.mode.as_deref(), Some("percent"));
        assert_eq!(rates[1].statement, "excess-rate-low");
        assert_eq!(rates[2].statement, "shaping-rate-priority-high");
        assert_eq!(rates[2].rate.value.as_deref(), Some("50m"));
        assert_eq!(rates[3].statement, "shaping-rate-excess-low");
        assert_eq!(rates[3].rate.burst_size.as_deref(), Some("8k"));
    }

    #[test]
    fn reads_the_other_options() {
        let profiles = profiles(EXTRA);
        let profile = &profiles[0];
        let overhead = profile.overhead_accounting.as_ref().unwrap();
        assert_eq!(overhead.mode, "frame-mode-bytes");
        assert_eq!(overhead.bytes.as_deref(), Some("20"));
        assert_eq!(profile.adjust_minimum.as_deref(), Some("1m"));
        assert_eq!(profile.atm_service.as_deref(), Some("cbr"));
        assert_eq!(profile.max_burst_size.as_deref(), Some("64"));
        assert_eq!(profile.peak_rate.as_deref(), Some("100m"));
        assert_eq!(profile.sustained_rate.as_deref(), Some("50m"));
        assert!(profile.granularity_mode_low && profile.queue_mode_4q && profile.strict_priority_scheduler);

        let plain = &profiles[1];
        assert_eq!(plain.overhead_accounting.as_ref().unwrap().mode, "cell-mode");
        assert_eq!(plain.overhead_accounting.as_ref().unwrap().bytes, None);
        assert!(plain.priority_rates.is_empty());
        assert!(!plain.queue_mode_4q);
    }
}