asterust-junos 0.4.1

Typed Juniper JunOS config views (interfaces, OSPF, BGP, IS-IS, routing instances, policy options, firewall filters, system) extracted from an asterust config tree.
Documentation
//! `schedulers`
//! `class-of-service { schedulers { <name> { ... } } }`.
//!
//! # See also
//!
//! - [schedulers](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/schedulers-edit-cos.html)
//! - [transmit-rate](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/transmit-rate-edit-cos.html)
//! - [buffer-size](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/buffer-size-edit-cos.html)
//! - [shaping-rate (schedulers)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/shaping-rate-edit-cos-schedulers.html)
//! - [excess-rate](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/excess-rate-edit-cos.html)
//! - [excess-priority](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/excess-priority-edit-cos.html)
//! - [priority (schedulers)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/priority-edit-cos-schedulers.html)
//! - [drop-profile-map](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/drop-profile-map-edit-cos.html)
//! - [Example: Configuring Class-of-Service Schedulers on a Security Device](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cos-security-devices/topics/example/cos-scheduler-security-configuring.html)
//! - [Example: Configuring Priority Scheduling](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cos-security-devices/topics/example/cos-priority-scheduling-security-configuring.html)

use super::words;
use crate::{active_children, arg_of, args_of, child_block, has_leaf, statement_words, value_after};
use asterust::config::ConfigLine;

/// A rate or size of a scheduler, such as `transmit-rate percent 45`, `shaping-rate 500m` or
/// `buffer-size temporal 100k`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SchedulerRate {
    /// `percent`, `remainder`, `proportion`, `temporal` or `shared`; `None` for an absolute value.
    pub mode: Option<String>,
    /// The value after the mode, or the absolute value.
    pub value: Option<String>,
    pub exact: bool,
    pub rate_limit: bool,
    pub burst_size: Option<String>,
}

/// A `drop-profile-map loss-priority <level> protocol <protocol> drop-profile <name>` entry.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropProfileMap {
    pub loss_priority: Option<String>,
    pub protocol: Option<String>,
    pub drop_profile: Option<String>,
}

/// A `schedulers` entry.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Scheduler {
    pub name: String,
    pub transmit_rate: Option<SchedulerRate>,
    pub shaping_rate: Option<SchedulerRate>,
    pub buffer_size: Option<SchedulerRate>,
    pub buffer_rate: Option<SchedulerRate>,
    pub excess_rate: Option<SchedulerRate>,
    pub priority: Option<String>,
    pub excess_priority: Vec<String>,
    pub adjust_minimum: Option<String>,
    pub adjust_percent: Option<String>,
    pub buffer_dynamic_threshold: Option<String>,
    pub explicit_congestion_notification: bool,
    /// The `threshold` of `latency-ecn`.
    pub latency_ecn_threshold: Option<String>,
    pub drop_profile_maps: Vec<DropProfileMap>,
}

const MODES: [&str; 5] = ["percent", "remainder", "proportion", "temporal", "shared"];

pub(super) fn parse_rate(words: &[&str]) -> SchedulerRate {
    let mode = words
        .first()
        .filter(|word| MODES.contains(*word))
        .map(|word| word.to_string());
    let value = words
        .get(usize::from(mode.is_some()))
        .filter(|word| !matches!(**word, "exact" | "rate-limit" | "burst-size"))
        .map(|word| word.to_string());
    SchedulerRate {
        mode,
        value,
        exact: words.contains(&"exact"),
        rate_limit: words.contains(&"rate-limit"),
        burst_size: value_after(words, "burst-size"),
    }
}

/// The rate written in the `<keyword>` statement of `line`.
pub(super) fn rate_of(line: &ConfigLine, keyword: &str) -> Option<SchedulerRate> {
    statement_words(line, keyword).map(|words| parse_rate(&words))
}

fn parse_drop_profile_map(arg: &str) -> DropProfileMap {
    let words: Vec<&str> = arg.split_whitespace().collect();
    DropProfileMap {
        loss_priority: value_after(&words, "loss-priority"),
        protocol: value_after(&words, "protocol"),
        drop_profile: value_after(&words, "drop-profile"),
    }
}

fn parse_scheduler(scheduler: &ConfigLine) -> Option<Scheduler> {
    let name = scheduler.text.split_whitespace().next()?;
    let rate = |keyword: &str| rate_of(scheduler, keyword);
    let field = |keyword: &str| arg_of(scheduler, keyword).map(str::to_string);
    Some(Scheduler {
        name: name.to_string(),
        transmit_rate: rate("transmit-rate"),
        shaping_rate: rate("shaping-rate"),
        buffer_size: rate("buffer-size"),
        buffer_rate: rate("buffer-rate"),
        excess_rate: rate("excess-rate"),
        priority: field("priority"),
        excess_priority: active_children(scheduler)
            .find(|child| child.text == "excess-priority" || child.arg("excess-priority").is_some())
            .map(|child| words(child, 1).into_iter().map(str::to_string).collect())
            .unwrap_or_default(),
        adjust_minimum: field("adjust-minimum"),
        adjust_percent: field("adjust-percent"),
        buffer_dynamic_threshold: field("buffer-dynamic-threshold"),
        explicit_congestion_notification: has_leaf(scheduler, "explicit-congestion-notification"),
        latency_ecn_threshold: statement_words(scheduler, "latency-ecn")
            .and_then(|words| value_after(&words, "threshold")),
        drop_profile_maps: args_of(scheduler, "drop-profile-map")
            .into_iter()
            .map(parse_drop_profile_map)
            .collect(),
    })
}

pub(super) fn parse_schedulers(cos: &ConfigLine) -> Vec<Scheduler> {
    let Some(block) = child_block(cos, "schedulers") else {
        return Vec::new();
    };
    active_children(block).filter_map(parse_scheduler).collect()
}

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

    // The `schedulers` of Example: Configuring Class-of-Service Schedulers on a Security Device, Example: Configuring
    // Priority Scheduling and Example: Configuring a Four-Level Scheduler Hierarchy (Class of Service User Guide for
    // Security Devices), wrapped in `class-of-service` and shortened; see the README "Sources".
    const DOC_SCHEDULERS: &str = r#"
class-of-service {
    schedulers {
        be-scheduler {
            transmit-rate remainder 40;
            buffer-size percent 40;
            priority low;
        }
        af-scheduler {
            transmit-rate percent 45;
            buffer-size percent 45;
            priority high;
            drop-profile-map loss-priority low protocol any drop-profile af-normal;
            drop-profile-map loss-priority high protocol any drop-profile af-with-PLP;
        }
        be-sched {
            priority medium-low;
        }
        sched-cvlan0-qx {
            transmit-rate 20m;
            buffer-size temporal 100k;
            priority low;
            drop-profile-map loss-priority low protocol any drop-profile dp-low;
        }
    }
}
"#;

    // Not from documentation: written from the CLI Reference. See the README "Sources".
    const EXTRA: &str = r#"
class-of-service {
    schedulers {
        voice {
            transmit-rate percent 10 exact;
            shaping-rate percent 20 burst-size 64k;
            buffer-rate percent 5;
            excess-rate proportion 100;
            excess-priority [ low medium-low ];
            adjust-minimum 1m;
            adjust-percent 90;
            buffer-dynamic-threshold 7;
            explicit-congestion-notification;
            latency-ecn threshold 5;
        }
        ctl {
            transmit-rate 2m rate-limit;
            excess-priority none;
            drop-profile-map loss-priority any protocol tcp drop-profile red;
        }
        bulk {
            transmit-rate remainder;
            buffer-size shared;
        }
    }
}
"#;

    fn schedulers(text: &str) -> Vec<super::Scheduler> {
        class_of_service(&juniper::parse_braces(text)).unwrap().schedulers
    }

    #[test]
    fn reads_the_guide_schedulers() {
        let schedulers = schedulers(DOC_SCHEDULERS);
        assert_eq!(schedulers.len(), 4);

        let be = &schedulers[0];
        assert_eq!(be.name, "be-scheduler");
        let transmit = be.transmit_rate.as_ref().unwrap();
        assert_eq!(transmit.mode.as_deref(), Some("remainder"));
        assert_eq!(transmit.value.as_deref(), Some("40"));
        assert_eq!(be.buffer_size.as_ref().unwrap().mode.as_deref(), Some("percent"));
        assert_eq!(be.priority.as_deref(), Some("low"));
        assert!(be.drop_profile_maps.is_empty());

        let af = &schedulers[1];
        assert_eq!(af.transmit_rate.as_ref().unwrap().value.as_deref(), Some("45"));
        assert_eq!(af.priority.as_deref(), Some("high"));
        assert_eq!(af.drop_profile_maps.len(), 2);
        assert_eq!(af.drop_profile_maps[1].loss_priority.as_deref(), Some("high"));
        assert_eq!(af.drop_profile_maps[1].protocol.as_deref(), Some("any"));
        assert_eq!(af.drop_profile_maps[1].drop_profile.as_deref(), Some("af-with-PLP"));

        assert_eq!(schedulers[2].priority.as_deref(), Some("medium-low"));
        assert_eq!(schedulers[2].transmit_rate, None);

        let cvlan = &schedulers[3];
        let absolute = cvlan.transmit_rate.as_ref().unwrap();
        assert_eq!(absolute.mode, None);
        assert_eq!(absolute.value.as_deref(), Some("20m"));
        let buffer = cvlan.buffer_size.as_ref().unwrap();
        assert_eq!(buffer.mode.as_deref(), Some("temporal"));
        assert_eq!(buffer.value.as_deref(), Some("100k"));
    }

    #[test]
    fn reads_the_scheduler_options() {
        let schedulers = schedulers(EXTRA);
        let voice = &schedulers[0];
        let transmit = voice.transmit_rate.as_ref().unwrap();
        assert!(transmit.exact && !transmit.rate_limit);
        assert_eq!(transmit.value.as_deref(), Some("10"));
        let shaping = voice.shaping_rate.as_ref().unwrap();
        assert_eq!(shaping.mode.as_deref(), Some("percent"));
        assert_eq!(shaping.burst_size.as_deref(), Some("64k"));
        assert_eq!(voice.buffer_rate.as_ref().unwrap().value.as_deref(), Some("5"));
        let excess = voice.excess_rate.as_ref().unwrap();
        assert_eq!(excess.mode.as_deref(), Some("proportion"));
        assert_eq!(excess.value.as_deref(), Some("100"));
        assert_eq!(voice.excess_priority, ["low", "medium-low"]);
        assert_eq!(voice.adjust_minimum.as_deref(), Some("1m"));
        assert_eq!(voice.adjust_percent.as_deref(), Some("90"));
        assert_eq!(voice.buffer_dynamic_threshold.as_deref(), Some("7"));
        assert!(voice.explicit_congestion_notification);
        assert_eq!(voice.latency_ecn_threshold.as_deref(), Some("5"));
    }

    #[test]
    fn reads_rate_limits_bare_modes_and_single_priorities() {
        let schedulers = schedulers(EXTRA);
        let ctl = &schedulers[1];
        let transmit = ctl.transmit_rate.as_ref().unwrap();
        assert!(transmit.rate_limit && !transmit.exact);
        assert_eq!(transmit.mode, None);
        assert_eq!(transmit.value.as_deref(), Some("2m"));
        assert_eq!(ctl.excess_priority, ["none"]);
        assert_eq!(ctl.drop_profile_maps[0].protocol.as_deref(), Some("tcp"));

        let bulk = &schedulers[2];
        let remainder = bulk.transmit_rate.as_ref().unwrap();
        assert_eq!(remainder.mode.as_deref(), Some("remainder"));
        assert_eq!(remainder.value, None);
        assert_eq!(bulk.buffer_size.as_ref().unwrap().mode.as_deref(), Some("shared"));
        assert!(!bulk.explicit_congestion_notification);
        assert!(bulk.excess_priority.is_empty());
    }
}