asterust-junos 0.4.2

Typed Juniper JunOS config views (interfaces, OSPF, BGP, IS-IS, routing instances, policy options, firewall filters, system) extracted from an asterust config tree.
Documentation
//! `rsvp`
//! `protocols { rsvp { ... } }`.
//!
//! # See also
//!
//! - [`[edit protocols rsvp]` hierarchy](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/topic-map/hierarchy-edit-protocols.html)
//! - [keep-multiplier](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/keep-multiplier-edit-protocols-rsvp.html)
//! - [refresh-time](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/refresh-time-edit-protocols-rsvp.html)
//! - [node-hello](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/node-hello-edit-protocols-rsvp.html)
//! - [no-enhanced-frr-bypass (Protocols RSVP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-enhanced-frr-bypass-edit-protocols-rsvp.html)
//! - [load-balance (Protocols RSVP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/load-balance-edit-protocols-rsvp.html)
//! - [preemption](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/preemption-edit-protocols-rsvp.html)
//! - [soft-preemption (Protocols RSVP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/soft-preemption-edit-protocols-rsvp.html)
//! - [graceful-restart (Protocols RSVP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/graceful-restart-edit-protocols-rsvp.html)
//! - [disable (Protocols RSVP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/disable-edit-protocols-rsvp.html)
//! - [traceoptions (Protocols RSVP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/traceoptions-edit-protocols-rsvp.html)
//! - [Basic MPLS Configuration](https://networkingdocs.hpe.com/documentation/us/en/software/junos/mpls/topics/topic-map/mpls-basic-configuration.html)
//! - [Link-State Distribution Using BGP](https://networkingdocs.hpe.com/documentation/us/en/software/junos/bgp/topics/topic-map/link-state-distribution-using-bgp.html)

mod interface;
mod link_protection;

pub use interface::RsvpInterface;
pub use link_protection::{RsvpBypass, RsvpLinkProtection};

use super::traceoptions::{parse_traceoptions, Traceoptions};
use crate::{arg_of, child_block, has_leaf, named_children, statement_words, toggle, top_level};
use asterust::config::{Config, ConfigLine};
use interface::parse_interface;

/// The `preemption` setting.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RsvpPreemption {
    /// `aggressive`, `disabled` or `normal`.
    pub mode: Option<String>,
    /// Seconds, from `soft-preemption { cleanup-timer ...; }`.
    pub soft_preemption_cleanup_timer: Option<String>,
}

/// The `graceful-restart` options.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RsvpGracefulRestart {
    pub disable: bool,
    pub helper_disable: bool,
    /// Seconds.
    pub maximum_helper_recovery_time: Option<String>,
    /// Seconds.
    pub maximum_helper_restart_time: Option<String>,
}

/// The `protocols rsvp` configuration. The `peer-interface`, `no-cspf`, `bandwidth`-model and `update-threshold`
/// statements outside interfaces are not extracted.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Rsvp {
    pub disable: bool,
    pub interfaces: Vec<RsvpInterface>,
    pub keep_multiplier: Option<String>,
    /// Seconds.
    pub refresh_time: Option<String>,
    /// `Some(true)` for `node-hello`, `Some(false)` for `no-node-hello`.
    pub node_hello: Option<bool>,
    pub no_enhanced_frr_bypass: bool,
    /// `load-balance { bandwidth; }`.
    pub load_balance_bandwidth: bool,
    pub preemption: Option<RsvpPreemption>,
    /// Seconds, from the `soft-preemption` statement directly under `rsvp`.
    pub soft_preemption_cleanup_timer: Option<String>,
    pub graceful_restart: Option<RsvpGracefulRestart>,
    pub traceoptions: Option<Traceoptions>,
}

/// Returns the `protocols rsvp` block, or `None` if RSVP is not configured.
///
/// # Examples
///
/// ```
/// use asterust::config::juniper;
/// use asterust_junos::protocols::rsvp::rsvp;
///
/// let config = juniper::parse_braces("protocols {\n    rsvp {\n        interface all;\n        interface fxp0.0 {\n            disable;\n        }\n    }\n}\n");
/// let rsvp = rsvp(&config).unwrap();
/// assert_eq!(rsvp.interfaces[0].name, "all");
/// assert!(rsvp.interfaces[1].disable);
/// ```
pub fn rsvp(config: &Config) -> Option<Rsvp> {
    let rsvp = child_block(top_level(config, "protocols")?, "rsvp")?;
    let field = |keyword: &str| arg_of(rsvp, keyword).map(str::to_string);
    Some(Rsvp {
        disable: has_leaf(rsvp, "disable"),
        interfaces: named_children(rsvp, "interface")
            .map(|(name, interface)| parse_interface(name, interface))
            .collect(),
        keep_multiplier: field("keep-multiplier"),
        refresh_time: field("refresh-time"),
        node_hello: toggle(rsvp, "node-hello"),
        no_enhanced_frr_bypass: has_leaf(rsvp, "no-enhanced-frr-bypass"),
        load_balance_bandwidth: statement_words(rsvp, "load-balance").is_some_and(|words| words.contains(&"bandwidth")),
        preemption: parse_preemption(rsvp),
        soft_preemption_cleanup_timer: child_block(rsvp, "soft-preemption")
            .and_then(|block| arg_of(block, "cleanup-timer"))
            .map(str::to_string),
        graceful_restart: parse_graceful_restart(rsvp),
        traceoptions: parse_traceoptions(rsvp),
    })
}

fn parse_preemption(rsvp: &ConfigLine) -> Option<RsvpPreemption> {
    let words = statement_words(rsvp, "preemption")?;
    Some(RsvpPreemption {
        mode: ["aggressive", "disabled", "normal"]
            .into_iter()
            .find(|mode| words.contains(mode))
            .map(str::to_string),
        soft_preemption_cleanup_timer: child_block(rsvp, "preemption")
            .and_then(|block| child_block(block, "soft-preemption"))
            .and_then(|soft| arg_of(soft, "cleanup-timer"))
            .map(str::to_string),
    })
}

fn parse_graceful_restart(rsvp: &ConfigLine) -> Option<RsvpGracefulRestart> {
    let block = child_block(rsvp, "graceful-restart")?;
    Some(RsvpGracefulRestart {
        disable: has_leaf(block, "disable"),
        helper_disable: has_leaf(block, "helper-disable"),
        maximum_helper_recovery_time: arg_of(block, "maximum-helper-recovery-time").map(str::to_string),
        maximum_helper_restart_time: arg_of(block, "maximum-helper-restart-time").map(str::to_string),
    })
}

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

    // Router R1 `show protocols` (RSVP part) of "Example: Configuring Link State Distribution Using BGP" (BGP User Guide)
    // and the provider switch of "Example: Configuring MPLS on EX8200 and EX4500 Switches" (MPLS Applications User
    // Guide, Basic MPLS Configuration); see the README "Sources".
    const DOC_RSVP: &str = r#"
protocols {
    rsvp {
        interface all;
        interface fxp0.0 {
            disable;
        }
    }
}
"#;

    const DOC_RSVP_PROVIDER: &str = r#"
protocols {
    rsvp {
        interface lo0.0;
        interface ge-0/0/5.0;
        interface ge-0/0/6.0;
        interface ae0.0;
    }
}
"#;

    // Not from documentation: written from the CLI Reference pages of the statements. See the README "Sources".
    const EXTRA: &str = r#"
protocols {
    rsvp {
        keep-multiplier 3;
        refresh-time 600;
        no-node-hello;
        no-enhanced-frr-bypass;
        load-balance {
            bandwidth;
        }
        preemption {
            aggressive;
            soft-preemption {
                cleanup-timer 60;
            }
        }
        soft-preemption {
            cleanup-timer 30;
        }
        graceful-restart {
            helper-disable;
            maximum-helper-recovery-time 120;
            maximum-helper-restart-time 180;
        }
        traceoptions {
            file rsvp.log size 1m;
            flag error;
        }
        interface ge-0/0/0.0 {
            no-aggregate;
            authentication-key "$9$secret"; ## SECRET-DATA
            bandwidth 800m;
            hello-interval 5;
            reliable;
            subscription 80;
            update-threshold 5;
            link-protection {
                admin-group {
                    exclude red;
                    include-any [ gold silver ];
                }
                bandwidth 100m;
                class-of-service 3;
                hop-limit 6;
                max-bypasses 2;
                no-cspf;
                no-node-protection;
                optimize-timer 300;
                path 10.0.0.9 strict;
                priority 5 5;
                subscription 90;
                bypass byp1 {
                    bandwidth 50m;
                    description "around R2";
                    class-of-service 2;
                    hop-limit 4;
                    no-cspf;
                    path 10.0.0.5 loose;
                    path 10.0.0.6 strict;
                    priority 6 6;
                    to 10.255.0.2;
                }
            }
        }
        interface ge-0/0/1.0 {
            link-protection {
                disable;
            }
        }
        interface ge-0/0/2.0 {
            link-protection;
        }
    }
}
"#;

    #[test]
    fn reads_the_guide_interfaces() {
        let rsvp = rsvp(&juniper::parse_braces(DOC_RSVP)).unwrap();
        assert_eq!(rsvp.interfaces.len(), 2);
        assert_eq!(rsvp.interfaces[0].name, "all");
        assert!(!rsvp.interfaces[0].disable);
        assert_eq!(rsvp.interfaces[1].name, "fxp0.0");
        assert!(rsvp.interfaces[1].disable);
        assert!(!rsvp.disable);

        let provider = rsvp_of(DOC_RSVP_PROVIDER);
        let names: Vec<&str> = provider.interfaces.iter().map(|i| i.name.as_str()).collect();
        assert_eq!(names, ["lo0.0", "ge-0/0/5.0", "ge-0/0/6.0", "ae0.0"]);
    }

    fn rsvp_of(text: &str) -> Rsvp {
        rsvp(&juniper::parse_braces(text)).unwrap()
    }

    #[test]
    fn reads_the_global_options() {
        let rsvp = rsvp_of(EXTRA);
        assert_eq!(rsvp.keep_multiplier.as_deref(), Some("3"));
        assert_eq!(rsvp.refresh_time.as_deref(), Some("600"));
        assert_eq!(rsvp.node_hello, Some(false));
        assert!(rsvp.no_enhanced_frr_bypass);
        assert!(rsvp.load_balance_bandwidth);
        assert_eq!(rsvp.soft_preemption_cleanup_timer.as_deref(), Some("30"));

        let preemption = rsvp.preemption.unwrap();
        assert_eq!(preemption.mode.as_deref(), Some("aggressive"));
        assert_eq!(preemption.soft_preemption_cleanup_timer.as_deref(), Some("60"));

        let restart = rsvp.graceful_restart.unwrap();
        assert!(restart.helper_disable);
        assert!(!restart.disable);
        assert_eq!(restart.maximum_helper_recovery_time.as_deref(), Some("120"));
        assert_eq!(restart.maximum_helper_restart_time.as_deref(), Some("180"));

        let trace = rsvp.traceoptions.unwrap();
        assert_eq!(trace.file.as_deref(), Some("rsvp.log"));
        assert_eq!(trace.flags[0].name, "error");
    }

    #[test]
    fn reads_the_interface_options_without_the_key() {
        let rsvp = rsvp_of(EXTRA);
        let interface = &rsvp.interfaces[0];
        assert_eq!(interface.aggregate, Some(false));
        assert!(interface.has_authentication_key);
        assert_eq!(
            interface.authentication_key.as_ref().map(crate::Secret::expose),
            crate::secret::expected("$9$secret")
        );
        assert_eq!(interface.bandwidth.as_deref(), Some("800m"));
        assert_eq!(interface.hello_interval.as_deref(), Some("5"));
        assert_eq!(interface.reliable, Some(true));
        assert_eq!(interface.subscription.as_deref(), Some("80"));
        assert_eq!(interface.update_threshold.as_deref(), Some("5"));
        assert!(!interface.disable);
    }

    #[test]
    fn reads_link_protection_and_bypasses() {
        let rsvp = rsvp_of(EXTRA);
        let protection = rsvp.interfaces[0].link_protection.as_ref().unwrap();
        assert!(!protection.disable);
        assert_eq!(protection.admin_group.exclude, ["red"]);
        assert_eq!(protection.admin_group.include_any, ["gold", "silver"]);
        assert_eq!(protection.bandwidth.as_deref(), Some("100m"));
        assert_eq!(protection.class_of_service.as_deref(), Some("3"));
        assert_eq!(protection.hop_limit.as_deref(), Some("6"));
        assert_eq!(protection.max_bypasses.as_deref(), Some("2"));
        assert!(protection.no_cspf);
        assert!(protection.no_node_protection);
        assert_eq!(protection.optimize_timer.as_deref(), Some("300"));
        assert_eq!(protection.path, ["10.0.0.9 strict"]);
        assert_eq!(protection.priority.as_deref(), Some("5 5"));
        assert_eq!(protection.subscription.as_deref(), Some("90"));

        assert_eq!(protection.bypasses.len(), 1);
        let bypass = &protection.bypasses[0];
        assert_eq!(bypass.name, "byp1");
        assert_eq!(bypass.bandwidth.as_deref(), Some("50m"));
        assert_eq!(bypass.description.as_deref(), Some("around R2"));
        assert_eq!(bypass.class_of_service.as_deref(), Some("2"));
        assert_eq!(bypass.hop_limit.as_deref(), Some("4"));
        assert!(bypass.no_cspf);
        assert_eq!(bypass.path, ["10.0.0.5 loose", "10.0.0.6 strict"]);
        assert_eq!(bypass.priority.as_deref(), Some("6 6"));
        assert_eq!(bypass.to.as_deref(), Some("10.255.0.2"));
    }

    #[test]
    fn reads_the_link_protection_forms() {
        let rsvp = rsvp_of(EXTRA);
        assert!(rsvp.interfaces[1].link_protection.as_ref().unwrap().disable);
        assert_eq!(rsvp.interfaces[2].link_protection, Some(RsvpLinkProtection::default()));
        assert_eq!(rsvp_of(DOC_RSVP).interfaces[0].link_protection, None);
    }

    #[test]
    fn no_rsvp_is_none() {
        let config = juniper::parse_braces("protocols {\n    ospf {\n        area 0.0.0.0;\n    }\n}\n");
        assert_eq!(rsvp(&config), None);
    }
}