asterust-junos 0.5.3

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
//! `l2vpn`
//! `routing-instances { <name> { protocols { l2vpn { ... } } } }`.
//!
//! A Layer 2 VPN only exists inside a routing instance, so it is read through
//! [`RoutingInstance::l2vpn`](crate::routing_instances::RoutingInstance::l2vpn). The BFD `oam` block is read at the
//! instance, site and interface levels; `neighbor` (Layer 2 VPN with LDP signaling) is not extracted.
//!
//! # See also
//!
//! - [l2vpn](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/l2vpn-edit-protocols.html)
//! - [control-word (Protocols Layer 2 VPN)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/control-word-edit-protocols-l2vpn.html)
//! - [no-control-word (Protocols Layer 2 VPN)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-control-word-edit-protocols-l2vpn.html)
//! - [encapsulation-type (Layer 2 VPNs)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/encapsulation-type-edit-protocols-l2vpn.html)
//! - [traceoptions (Protocols Layer 2 VPN)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/traceoptions-edit-protocols-l2vpn.html)
//! - [site (Layer 2 VPNs and Circuits)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/site-edit-protocols-l2vpn.html)
//! - [site-identifier (Layer 2 Circuits)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/site-identifier-edit-protocols-l2vpn.html)
//! - [site-preference](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/site-preference-edit-protocols-l2vpn.html)
//! - [interface (Protocols Layer 2 VPN)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/interface-edit-protocols-l2vpn.html)
//! - [remote-site-id](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/remote-site-id-edit-protocols-l2vpn.html)
//! - [ignore-encapsulation-mismatch](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/ignore-encapsulation-mismatch-edit-protocols-l2circuit.html)
//! - [ignore-mtu-mismatch](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/ignore-mtu-mismatch-edit-protocols-l2circuit.html)
//! - [ping-interval](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/ping-interval-edit-routing-instances.html)
//! - [source-attachment-identifier](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/source-attachment-identifier-edit-routing-instances.html)
//! - [target-attachment-identifier](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/target-attachment-identifier-edit-routing-instances.html)
//! - [Configuring the Local Site on PE Routers in Layer 2 VPNs](https://networkingdocs.hpe.com/documentation/us/en/software/junos/vpn-l2/topics/concept/vpns-configuring-the-local-site-on-pe-routers-in-layer-2-vpns.html), for `description` and the other statements without a page of their own

use super::traceoptions::{parse_traceoptions, Traceoptions};
use crate::{arg_of, child_block, has_leaf, named_children, split_name, statement_words, toggle, value_after};
use asterust::config::ConfigLine;

/// The BFD session of the `oam` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct L2vpnBfd {
    /// Milliseconds.
    pub minimum_interval: Option<String>,
    pub minimum_receive_interval: Option<String>,
    pub multiplier: Option<String>,
    /// `1` or `automatic`.
    pub version: Option<String>,
    pub no_adaptation: bool,
    /// From `detection-time { threshold ...; }`.
    pub detection_time_threshold: Option<String>,
    /// From `transmit-interval { minimum-interval ...; }`.
    pub transmit_interval_minimum: Option<String>,
    /// From `transmit-interval { threshold ...; }`.
    pub transmit_interval_threshold: Option<String>,
}

/// The `oam` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct L2vpnOam {
    /// Seconds.
    pub ping_interval: Option<String>,
    pub bfd_liveness_detection: Option<L2vpnBfd>,
}

/// The settings that a Layer 2 VPN, one of its sites and one of its interfaces can each carry.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct L2vpnOptions {
    /// `Some(true)` for `control-word`, `Some(false)` for `no-control-word`.
    pub control_word: Option<bool>,
    /// From `encapsulation-type`, or `encapsulation` on EX9200.
    pub encapsulation_type: Option<String>,
    pub ignore_encapsulation_mismatch: bool,
    pub ignore_mtu_mismatch: bool,
    pub mtu: Option<String>,
    pub oam: Option<L2vpnOam>,
}

/// An `interface <name>` of a site.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct L2vpnInterface {
    pub name: String,
    pub description: Option<String>,
    pub community: Option<String>,
    pub remote_site_id: Option<String>,
    pub target_attachment_identifier: Option<String>,
    pub options: L2vpnOptions,
}

/// A `site <name>` of a Layer 2 VPN.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct L2vpnSite {
    pub name: String,
    pub community: Option<String>,
    pub hot_standby: bool,
    pub interfaces: Vec<L2vpnInterface>,
    pub site_identifier: Option<String>,
    /// The preference value, or `backup` or `primary`, as written after `site-preference`.
    pub site_preference: Option<String>,
    /// `backup` or `primary`, from the block form of `site-preference`.
    pub site_preference_role: Option<String>,
    pub source_attachment_identifier: Option<String>,
    /// The label of `static incoming-label`.
    pub static_incoming_label: Option<String>,
    pub options: L2vpnOptions,
}

/// The `protocols l2vpn` configuration of a routing instance.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct L2vpn {
    pub options: L2vpnOptions,
    pub sites: Vec<L2vpnSite>,
    pub traceoptions: Option<Traceoptions>,
}

fn parse_bfd(bfd: &ConfigLine) -> L2vpnBfd {
    let field = |keyword: &str| arg_of(bfd, keyword).map(str::to_string);
    let nested = |block: &str, keyword: &str| {
        child_block(bfd, block)
            .and_then(|block| arg_of(block, keyword))
            .map(str::to_string)
    };
    L2vpnBfd {
        minimum_interval: field("minimum-interval"),
        minimum_receive_interval: field("minimum-receive-interval"),
        multiplier: field("multiplier"),
        version: field("version"),
        no_adaptation: has_leaf(bfd, "no-adaptation"),
        detection_time_threshold: nested("detection-time", "threshold"),
        transmit_interval_minimum: nested("transmit-interval", "minimum-interval"),
        transmit_interval_threshold: nested("transmit-interval", "threshold"),
    }
}

fn parse_options(line: &ConfigLine) -> L2vpnOptions {
    L2vpnOptions {
        control_word: toggle(line, "control-word"),
        encapsulation_type: arg_of(line, "encapsulation-type")
            .or_else(|| arg_of(line, "encapsulation"))
            .map(str::to_string),
        ignore_encapsulation_mismatch: has_leaf(line, "ignore-encapsulation-mismatch"),
        ignore_mtu_mismatch: has_leaf(line, "ignore-mtu-mismatch"),
        mtu: arg_of(line, "mtu").map(str::to_string),
        oam: child_block(line, "oam").map(|oam| L2vpnOam {
            ping_interval: arg_of(oam, "ping-interval").map(str::to_string),
            bfd_liveness_detection: child_block(oam, "bfd-liveness-detection").map(parse_bfd),
        }),
    }
}

fn parse_interface(arg: &str, interface: &ConfigLine) -> L2vpnInterface {
    let (name, rest) = split_name(arg);
    let words: Vec<&str> = rest.split_whitespace().collect();
    L2vpnInterface {
        name: name.to_string(),
        description: arg_of(interface, "description").map(str::to_string),
        community: arg_of(interface, "community").map(str::to_string),
        remote_site_id: arg_of(interface, "remote-site-id")
            .map(str::to_string)
            .or_else(|| value_after(&words, "remote-site-id")),
        target_attachment_identifier: arg_of(interface, "target-attachment-identifier").map(str::to_string),
        options: parse_options(interface),
    }
}

fn parse_site(name: &str, site: &ConfigLine) -> L2vpnSite {
    let preference = child_block(site, "site-preference")
        .or_else(|| named_children(site, "site-preference").next().map(|(_, block)| block));
    L2vpnSite {
        name: name.to_string(),
        community: arg_of(site, "community").map(str::to_string),
        hot_standby: has_leaf(site, "hot-standby"),
        interfaces: named_children(site, "interface")
            .map(|(arg, interface)| parse_interface(arg, interface))
            .collect(),
        site_identifier: arg_of(site, "site-identifier").map(str::to_string),
        site_preference: arg_of(site, "site-preference").map(str::to_string),
        site_preference_role: preference.and_then(|block| {
            ["backup", "primary"]
                .into_iter()
                .find(|role| has_leaf(block, role))
                .map(str::to_string)
        }),
        source_attachment_identifier: arg_of(site, "source-attachment-identifier").map(str::to_string),
        static_incoming_label: statement_words(site, "static").and_then(|words| value_after(&words, "incoming-label")),
        options: parse_options(site),
    }
}

/// Reads the `l2vpn` block of an instance's `protocols` block.
pub(crate) fn parse_l2vpn(protocols: &ConfigLine) -> Option<L2vpn> {
    let l2vpn = child_block(protocols, "l2vpn")?;
    Some(L2vpn {
        options: parse_options(l2vpn),
        sites: named_children(l2vpn, "site")
            .map(|(name, site)| parse_site(name, site))
            .collect(),
        traceoptions: parse_traceoptions(l2vpn),
    })
}

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

    // Not from documentation: written from the CLI Reference and the Configuring the Local Site on PE Routers in
    // Layer 2 VPNs statement summary. See the README "Sources".
    const CONFIG: &str = r#"
routing-instances {
    CE-A {
        instance-type l2vpn;
        interface ge-0/0/1.600;
        route-distinguisher 65000:600;
        vrf-target target:65000:600;
        protocols {
            l2vpn {
                encapsulation-type ethernet-vlan;
                no-control-word;
                traceoptions {
                    file l2vpn.log size 1m;
                    flag all;
                }
                oam {
                    ping-interval 10;
                    bfd-liveness-detection {
                        minimum-interval 300;
                        minimum-receive-interval 400;
                        multiplier 3;
                        version automatic;
                        no-adaptation;
                        detection-time {
                            threshold 1000;
                        }
                        transmit-interval {
                            minimum-interval 200;
                            threshold 500;
                        }
                    }
                }
                site CE-A-1 {
                    site-identifier 1;
                    site-preference 200 {
                        primary;
                    }
                    hot-standby;
                    ignore-mtu-mismatch;
                    mtu 1500;
                    source-attachment-identifier 10;
                    static {
                        incoming-label 1000;
                    }
                    interface ge-0/0/1.600 {
                        description "to CE-A";
                        remote-site-id 2;
                        encapsulation-type ethernet;
                        control-word;
                        ignore-encapsulation-mismatch;
                        community COMM;
                        target-attachment-identifier 20;
                    }
                    interface ge-0/0/2.600 remote-site-id 3;
                }
                site CE-A-2 {
                    site-identifier 2;
                    site-preference backup;
                }
            }
        }
    }
    CUSTOMER-B {
        instance-type vrf;
    }
}
"#;

    fn instances() -> Vec<crate::routing_instances::RoutingInstance> {
        routing_instances(&juniper::parse_braces(CONFIG))
    }

    #[test]
    fn reads_the_instance_level_options() {
        let instances = instances();
        let l2vpn = instances[0].l2vpn.as_ref().unwrap();
        assert_eq!(l2vpn.options.encapsulation_type.as_deref(), Some("ethernet-vlan"));
        assert_eq!(l2vpn.options.control_word, Some(false));
        let trace = l2vpn.traceoptions.as_ref().unwrap();
        assert_eq!(trace.file.as_deref(), Some("l2vpn.log"));
        assert_eq!(trace.flags[0].name, "all");
        assert_eq!(l2vpn.sites.len(), 2);
    }

    #[test]
    fn reads_the_oam_block() {
        let instances = instances();
        let oam = instances[0].l2vpn.as_ref().unwrap().options.oam.as_ref().unwrap();
        assert_eq!(oam.ping_interval.as_deref(), Some("10"));
        let bfd = oam.bfd_liveness_detection.as_ref().unwrap();
        assert_eq!(bfd.minimum_interval.as_deref(), Some("300"));
        assert_eq!(bfd.minimum_receive_interval.as_deref(), Some("400"));
        assert_eq!(bfd.multiplier.as_deref(), Some("3"));
        assert_eq!(bfd.version.as_deref(), Some("automatic"));
        assert!(bfd.no_adaptation);
        assert_eq!(bfd.detection_time_threshold.as_deref(), Some("1000"));
        assert_eq!(bfd.transmit_interval_minimum.as_deref(), Some("200"));
        assert_eq!(bfd.transmit_interval_threshold.as_deref(), Some("500"));
    }

    #[test]
    fn reads_the_site_options() {
        let instances = instances();
        let site = &instances[0].l2vpn.as_ref().unwrap().sites[0];
        assert_eq!(site.name, "CE-A-1");
        assert_eq!(site.site_identifier.as_deref(), Some("1"));
        assert_eq!(site.site_preference.as_deref(), Some("200"));
        assert_eq!(site.site_preference_role.as_deref(), Some("primary"));
        assert!(site.hot_standby);
        assert!(site.options.ignore_mtu_mismatch);
        assert_eq!(site.options.mtu.as_deref(), Some("1500"));
        assert_eq!(site.source_attachment_identifier.as_deref(), Some("10"));
        assert_eq!(site.static_incoming_label.as_deref(), Some("1000"));
    }

    #[test]
    fn reads_the_interfaces_in_both_forms() {
        let instances = instances();
        let site = &instances[0].l2vpn.as_ref().unwrap().sites[0];
        assert_eq!(site.interfaces.len(), 2);
        let block = &site.interfaces[0];
        assert_eq!(block.name, "ge-0/0/1.600");
        assert_eq!(block.description.as_deref(), Some("to CE-A"));
        assert_eq!(block.remote_site_id.as_deref(), Some("2"));
        assert_eq!(block.options.encapsulation_type.as_deref(), Some("ethernet"));
        assert_eq!(block.options.control_word, Some(true));
        assert!(block.options.ignore_encapsulation_mismatch);
        assert_eq!(block.community.as_deref(), Some("COMM"));
        assert_eq!(block.target_attachment_identifier.as_deref(), Some("20"));

        let inline = &site.interfaces[1];
        assert_eq!(inline.name, "ge-0/0/2.600");
        assert_eq!(inline.remote_site_id.as_deref(), Some("3"));
    }

    #[test]
    fn reads_the_keyword_site_preference() {
        let instances = instances();
        let site = &instances[0].l2vpn.as_ref().unwrap().sites[1];
        assert_eq!(site.site_preference.as_deref(), Some("backup"));
        assert_eq!(site.site_preference_role, None);
        assert!(!site.hot_standby);
        assert!(site.interfaces.is_empty());
    }

    #[test]
    fn other_instances_have_no_l2vpn() {
        assert_eq!(instances()[1].l2vpn, None);
    }

    #[test]
    fn the_ex9200_encapsulation_statement_is_read() {
        let instances = routing_instances(&juniper::parse_braces(
            "routing-instances {\n    A {\n        protocols {\n            l2vpn {\n                encapsulation ethernet;\n            }\n        }\n    }\n}\n",
        ));
        let l2vpn = instances[0].l2vpn.as_ref().unwrap();
        assert_eq!(l2vpn.options.encapsulation_type.as_deref(), Some("ethernet"));
    }
}