asterust-junos 0.5.6

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
//! `application-traffic-control`
//! `class-of-service { application-traffic-control { rate-limiters { ... } rule-sets <name> { ... } } }`.
//!
//! # See also
//!
//! - [application-traffic-control](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/class-of-service-edit-application-traffic-control.html)
//! - [rate-limiters](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/class-of-service-edit-rate-limiters.html)

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

/// A `rate-limiters` entry.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RateLimiter {
    pub name: String,
    /// Kilobits per second.
    pub bandwidth_limit: Option<String>,
    /// Bytes.
    pub burst_size_limit: Option<String>,
}

/// The `rate-limit` action of a rule.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RuleRateLimit {
    pub loss_priority_high: bool,
    pub client_to_server: Option<String>,
    pub server_to_client: Option<String>,
}

/// A `rule <name>` of a rule set.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AppQosRule {
    pub name: String,
    /// The `application` names of `match`.
    pub applications: Vec<String>,
    pub application_groups: Vec<String>,
    /// `application-any`, `application-known` and `application-unknown`, as written.
    pub application_flags: Vec<String>,
    pub dscp_code_point: Option<String>,
    pub forwarding_class: Option<String>,
    pub log: bool,
    pub loss_priority: Vec<String>,
    pub rate_limit: Option<RuleRateLimit>,
}

/// A `rule-sets` entry.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AppQosRuleSet {
    pub name: String,
    pub rules: Vec<AppQosRule>,
}

/// The `application-traffic-control` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ApplicationTrafficControl {
    pub rate_limiters: Vec<RateLimiter>,
    pub rule_sets: Vec<AppQosRuleSet>,
}

fn parse_rule(name: &str, rule: &ConfigLine) -> AppQosRule {
    let matches = child_block(rule, "match");
    let then = child_block(rule, "then");
    let list = |block: Option<&ConfigLine>, keyword: &str| -> Vec<String> {
        block
            .map(|block| args_of(block, keyword).into_iter().map(str::to_string).collect())
            .unwrap_or_default()
    };
    AppQosRule {
        name: name.to_string(),
        applications: list(matches, "application"),
        application_groups: list(matches, "application-group"),
        application_flags: matches
            .map(|block| {
                active_children(block)
                    .map(|child| child.text.as_str())
                    .filter(|text| matches!(*text, "application-any" | "application-known" | "application-unknown"))
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default(),
        dscp_code_point: then
            .and_then(|block| arg_of(block, "dscp-code-point"))
            .map(str::to_string),
        forwarding_class: then
            .and_then(|block| arg_of(block, "forwarding-class"))
            .map(str::to_string),
        log: then.is_some_and(|block| has_leaf(block, "log")),
        loss_priority: then
            .and_then(|block| arg_of(block, "loss-priority"))
            .map(list_values)
            .unwrap_or_default(),
        rate_limit: then.and_then(|block| child_block(block, "rate-limit")).map(|limit| {
            let words = words(limit, 0);
            RuleRateLimit {
                loss_priority_high: has_leaf(limit, "loss-priority-high"),
                client_to_server: value_after(&words, "client-to-server"),
                server_to_client: value_after(&words, "server-to-client"),
            }
        }),
    }
}

pub(super) fn parse_application_traffic_control(cos: &ConfigLine) -> Option<ApplicationTrafficControl> {
    let control = child_block(cos, "application-traffic-control")?;
    Some(ApplicationTrafficControl {
        rate_limiters: child_block(control, "rate-limiters")
            .map(|block| {
                active_children(block)
                    .filter_map(|limiter| {
                        Some(RateLimiter {
                            name: limiter.text.split_whitespace().next()?.to_string(),
                            bandwidth_limit: arg_of(limiter, "bandwidth-limit").map(str::to_string),
                            burst_size_limit: arg_of(limiter, "burst-size-limit").map(str::to_string),
                        })
                    })
                    .collect()
            })
            .unwrap_or_default(),
        rule_sets: named_children(control, "rule-sets")
            .map(|(name, set)| AppQosRuleSet {
                name: name.to_string(),
                rules: named_children(set, "rule")
                    .map(|(rule, line)| parse_rule(rule, line))
                    .collect(),
            })
            .collect(),
    })
}

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

    // Not from documentation: written from the CLI Reference. See the README "Sources".
    const EXTRA: &str = r#"
class-of-service {
    application-traffic-control {
        rate-limiters {
            LIMIT-A {
                bandwidth-limit 1000;
                burst-size-limit 4000;
            }
        }
        rule-sets VIDEO {
            rule R1 {
                match {
                    application junos:youtube;
                    application junos:netflix;
                    application-group streaming;
                    application-known;
                }
                then {
                    dscp-code-point af11;
                    forwarding-class assured-forwarding;
                    log;
                    loss-priority [ low medium-low ];
                    rate-limit {
                        loss-priority-high;
                        client-to-server LIMIT-A;
                        server-to-client LIMIT-A;
                    }
                }
            }
            rule R2 {
                match {
                    application-any;
                }
            }
        }
    }
}
"#;

    #[test]
    fn reads_the_rate_limiters() {
        let control = class_of_service(&juniper::parse_braces(EXTRA))
            .unwrap()
            .application_traffic_control
            .unwrap();
        assert_eq!(control.rate_limiters.len(), 1);
        assert_eq!(control.rate_limiters[0].name, "LIMIT-A");
        assert_eq!(control.rate_limiters[0].bandwidth_limit.as_deref(), Some("1000"));
        assert_eq!(control.rate_limiters[0].burst_size_limit.as_deref(), Some("4000"));
    }

    #[test]
    fn reads_the_rule_sets() {
        let control = class_of_service(&juniper::parse_braces(EXTRA))
            .unwrap()
            .application_traffic_control
            .unwrap();
        assert_eq!(control.rule_sets.len(), 1);
        let set = &control.rule_sets[0];
        assert_eq!(set.name, "VIDEO");
        assert_eq!(set.rules.len(), 2);
        let rule = &set.rules[0];
        assert_eq!(rule.name, "R1");
        assert_eq!(rule.applications, ["junos:youtube", "junos:netflix"]);
        assert_eq!(rule.application_groups, ["streaming"]);
        assert_eq!(rule.application_flags, ["application-known"]);
        assert_eq!(rule.dscp_code_point.as_deref(), Some("af11"));
        assert_eq!(rule.forwarding_class.as_deref(), Some("assured-forwarding"));
        assert!(rule.log);
        assert_eq!(rule.loss_priority, ["low", "medium-low"]);
        let limit = rule.rate_limit.as_ref().unwrap();
        assert!(limit.loss_priority_high);
        assert_eq!(limit.client_to_server.as_deref(), Some("LIMIT-A"));
        assert_eq!(limit.server_to_client.as_deref(), Some("LIMIT-A"));
    }

    #[test]
    fn a_rule_without_actions_has_none() {
        let control = class_of_service(&juniper::parse_braces(EXTRA))
            .unwrap()
            .application_traffic_control
            .unwrap();
        let rule = &control.rule_sets[0].rules[1];
        assert_eq!(rule.application_flags, ["application-any"]);
        assert!(rule.applications.is_empty());
        assert!(!rule.log && rule.rate_limit.is_none() && rule.dscp_code_point.is_none());
    }
}