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
//! `lldp-med`
//! `protocols { lldp-med { ... } }`.
//!
//! The CLI Reference has no `lldp-med` page, so the statements come from the Device Discovery using LLDP and LLDP-MED
//! page of the User Access guide. The `enable` and `disable` statements are read as for `protocols lldp`.
//!
//! # See also
//!
//! - [Device Discovery using LLDP and LLDP-MED](https://networkingdocs.hpe.com/documentation/us/en/software/junos/user-access/topics/topic-map/device-discovery-using-lldp-lldp-med.html)

use super::lldp::{enabled, names};
use crate::{active_children, arg_of, child_block, named_children, split_name, top_level};
use asterust::config::{Config, ConfigLine};

/// A `ca-type <type> ca-value <value>` element of a civic address.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CivicAddressElement {
    pub ca_type: String,
    pub ca_value: Option<String>,
}

/// The `civic-based` location of an interface.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CivicLocation {
    pub country_code: Option<String>,
    pub elements: Vec<CivicAddressElement>,
}

/// The `location` of an interface: a civic address or an ELIN.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct LldpMedLocation {
    pub civic_based: Option<CivicLocation>,
    /// The Emergency Location Identification Number.
    pub elin: Option<String>,
}

/// An `interface <name>` entry of LLDP-MED; the name can be `all`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LldpMedInterface {
    pub name: String,
    /// `Some(true)` for `enable`, `Some(false)` for `disable`.
    pub enabled: Option<bool>,
    pub tlv_filter: Vec<String>,
    pub tlv_select: Vec<String>,
    pub location: Option<LldpMedLocation>,
}

/// The `protocols lldp-med` configuration.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct LldpMed {
    /// `Some(true)` for `enable`, `Some(false)` for `disable`.
    pub enabled: Option<bool>,
    /// The number of advertisements sent in the first second after an LLDP-MED device is detected.
    pub fast_start: Option<String>,
    pub tlv_filter: Vec<String>,
    pub tlv_select: Vec<String>,
    pub interfaces: Vec<LldpMedInterface>,
}

fn parse_element(element: &ConfigLine) -> Option<CivicAddressElement> {
    let (ca_type, rest) = split_name(element.arg("ca-type")?);
    // The value follows `ca-value` on the same line, or is a `ca-value` child.
    let inline = rest
        .strip_prefix("ca-value")
        .map(|value| split_name(value.trim()).0.to_string());
    Some(CivicAddressElement {
        ca_type: ca_type.to_string(),
        ca_value: inline.or_else(|| arg_of(element, "ca-value").map(str::to_string)),
    })
}

fn parse_location(location: &ConfigLine) -> LldpMedLocation {
    LldpMedLocation {
        civic_based: child_block(location, "civic-based").map(|civic| CivicLocation {
            country_code: arg_of(civic, "country-code").map(str::to_string),
            elements: active_children(civic).filter_map(parse_element).collect(),
        }),
        elin: arg_of(location, "elin").map(str::to_string),
    }
}

fn parse_interface(name: &str, interface: &ConfigLine) -> LldpMedInterface {
    LldpMedInterface {
        name: name.to_string(),
        enabled: enabled(interface),
        tlv_filter: names(interface, "tlv-filter"),
        tlv_select: names(interface, "tlv-select"),
        location: child_block(interface, "location").map(parse_location),
    }
}

/// Returns the `protocols lldp-med` block, or `None` if LLDP-MED is not configured.
///
/// # Examples
///
/// ```
/// use asterust::config::juniper;
/// use asterust_junos::protocols::lldp_med::lldp_med;
///
/// let config = juniper::parse_braces("protocols {\n    lldp-med {\n        fast-start 6;\n    }\n}\n");
/// assert_eq!(lldp_med(&config).unwrap().fast_start.as_deref(), Some("6"));
/// ```
pub fn lldp_med(config: &Config) -> Option<LldpMed> {
    let med = child_block(top_level(config, "protocols")?, "lldp-med")?;
    Some(LldpMed {
        enabled: enabled(med),
        fast_start: arg_of(med, "fast-start").map(str::to_string),
        tlv_filter: names(med, "tlv-filter"),
        tlv_select: names(med, "tlv-select"),
        interfaces: named_children(med, "interface")
            .map(|(name, interface)| parse_interface(name, interface))
            .collect(),
    })
}

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

    // The `lldp-med` statements of Configuring LLDP-MED (Device Discovery using LLDP and LLDP-MED, User Access guide),
    // written in brace form with the guide's examples; see the README "Sources".
    const DOC_EXAMPLE: &str = r#"
protocols {
    lldp-med {
        fast-start 6;
        tlv-select [ location-id ext-power-via-mdi ];
        interface ge-0/0/1 {
            tlv-filter network-policy;
        }
        interface ge-0/0/2.0 {
            location {
                elin 4085551212;
            }
        }
        interface ge-2/1/1 {
            tlv-filter ext-power-via-mdi;
        }
    }
}
"#;

    // Not from documentation: written from the statements shown in the guide, whose civic address values are
    // placeholders. See the README "Sources".
    const EXTRA: &str = r#"
protocols {
    lldp-med {
        disable;
        interface all;
        interface ge-0/0/3.0 {
            enable;
            location {
                civic-based {
                    country-code US;
                    ca-type 1 {
                        ca-value California;
                    }
                    ca-type 3 ca-value "Santa Clara";
                }
            }
        }
    }
}
"#;

    fn med(text: &str) -> LldpMed {
        lldp_med(&juniper::parse_braces(text)).unwrap()
    }

    #[test]
    fn reads_the_guide_example() {
        let med = med(DOC_EXAMPLE);
        assert_eq!(med.fast_start.as_deref(), Some("6"));
        assert_eq!(med.tlv_select, ["location-id", "ext-power-via-mdi"]);
        assert!(med.tlv_filter.is_empty());
        assert_eq!(med.interfaces.len(), 3);
        assert_eq!(med.interfaces[0].name, "ge-0/0/1");
        assert_eq!(med.interfaces[0].tlv_filter, ["network-policy"]);
        let location = med.interfaces[1].location.as_ref().unwrap();
        assert_eq!(location.elin.as_deref(), Some("4085551212"));
        assert_eq!(location.civic_based, None);
        assert_eq!(med.interfaces[2].tlv_filter, ["ext-power-via-mdi"]);
    }

    #[test]
    fn reads_the_civic_location() {
        let med = med(EXTRA);
        assert_eq!(med.enabled, Some(false));
        assert_eq!(med.interfaces[0].name, "all");
        assert_eq!(med.interfaces[0].enabled, None);
        let interface = &med.interfaces[1];
        assert_eq!(interface.enabled, Some(true));
        let civic = interface.location.as_ref().unwrap().civic_based.as_ref().unwrap();
        assert_eq!(civic.country_code.as_deref(), Some("US"));
        assert_eq!(civic.elements.len(), 2);
        assert_eq!(civic.elements[0].ca_type, "1");
        assert_eq!(civic.elements[0].ca_value.as_deref(), Some("California"));
        assert_eq!(civic.elements[1].ca_type, "3");
        assert_eq!(civic.elements[1].ca_value.as_deref(), Some("Santa Clara"));
    }

    #[test]
    fn a_bare_lldp_med_block_has_nothing_set() {
        assert_eq!(med("protocols {\n    lldp-med;\n}\n"), LldpMed::default());
    }

    #[test]
    fn no_lldp_med_is_none() {
        let config = juniper::parse_braces("protocols {\n    lldp {\n        interface all;\n    }\n}\n");
        assert_eq!(lldp_med(&config), None);
    }
}