asterust-junos 0.5.4

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
//! `forwarding-policy`
//! `class-of-service { forwarding-policy { next-hop-map <name> { ... } class <name> { ... } } }`.
//!
//! # See also
//!
//! - [forwarding-policy](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/forwarding-policy-edit-cos.html)
//! - [next-hop-map](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/next-hop-map-edit-cos.html)
//! - [classification-override](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/classification-override-edit-cos.html)

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

/// A `forwarding-class <name>` or `forwarding-class-default` entry of a next-hop map.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct NextHopMapClass {
    /// `None` for `forwarding-class-default`.
    pub forwarding_class: Option<String>,
    pub discard: bool,
    pub lsp_next_hops: Vec<String>,
    pub next_hops: Vec<String>,
    pub non_lsp_next_hop: bool,
}

/// A `next-hop-map <name>` of a forwarding policy.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct NextHopMap {
    pub name: String,
    pub classes: Vec<NextHopMapClass>,
}

/// A `class <name>` of a forwarding policy.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ForwardingPolicyClass {
    pub name: String,
    /// The forwarding class of `classification-override`.
    pub classification_override: Option<String>,
}

/// The `forwarding-policy` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ForwardingPolicy {
    pub next_hop_maps: Vec<NextHopMap>,
    pub classes: Vec<ForwardingPolicyClass>,
}

fn parse_class(forwarding_class: Option<String>, line: &ConfigLine) -> NextHopMapClass {
    let names = |keyword: &str| args_of(line, keyword).into_iter().flat_map(list_values).collect();
    NextHopMapClass {
        forwarding_class,
        discard: has_leaf(line, "discard"),
        lsp_next_hops: names("lsp-next-hop"),
        next_hops: names("next-hop"),
        non_lsp_next_hop: has_leaf(line, "non-lsp-next-hop"),
    }
}

fn parse_map(name: &str, map: &ConfigLine) -> NextHopMap {
    NextHopMap {
        name: name.to_string(),
        classes: active_children(map)
            .filter_map(|child| {
                if let Some(class) = child.arg("forwarding-class") {
                    let name = class.split_whitespace().next()?;
                    Some(parse_class(Some(name.to_string()), child))
                } else if child.text == "forwarding-class-default" {
                    Some(parse_class(None, child))
                } else {
                    None
                }
            })
            .collect(),
    }
}

pub(super) fn parse_forwarding_policy(cos: &ConfigLine) -> Option<ForwardingPolicy> {
    let policy = child_block(cos, "forwarding-policy")?;
    Some(ForwardingPolicy {
        next_hop_maps: named_children(policy, "next-hop-map")
            .map(|(name, map)| parse_map(name, map))
            .collect(),
        classes: named_children(policy, "class")
            .map(|(name, class)| ForwardingPolicyClass {
                name: name.to_string(),
                classification_override: child_block(class, "classification-override")
                    .and_then(|block| arg_of(block, "forwarding-class"))
                    .map(str::to_string),
            })
            .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 {
    forwarding-policy {
        next-hop-map EF-TO-LSP {
            forwarding-class expedited-forwarding {
                lsp-next-hop [ lsp-ef-1 lsp-ef-2 ];
                non-lsp-next-hop;
            }
            forwarding-class assured-forwarding {
                next-hop 192.0.2.1;
            }
            forwarding-class best-effort {
                discard;
            }
            forwarding-class-default {
                lsp-next-hop lsp-default;
            }
        }
        class voice {
            classification-override {
                forwarding-class expedited-forwarding;
            }
        }
        class plain;
    }
}
"#;

    #[test]
    fn reads_the_next_hop_maps() {
        let policy = class_of_service(&juniper::parse_braces(EXTRA))
            .unwrap()
            .forwarding_policy
            .unwrap();
        assert_eq!(policy.next_hop_maps.len(), 1);
        let map = &policy.next_hop_maps[0];
        assert_eq!(map.name, "EF-TO-LSP");
        assert_eq!(map.classes.len(), 4);
        assert_eq!(map.classes[0].forwarding_class.as_deref(), Some("expedited-forwarding"));
        assert_eq!(map.classes[0].lsp_next_hops, ["lsp-ef-1", "lsp-ef-2"]);
        assert!(map.classes[0].non_lsp_next_hop && !map.classes[0].discard);
        assert_eq!(map.classes[1].next_hops, ["192.0.2.1"]);
        assert!(map.classes[2].discard);
        assert_eq!(map.classes[3].forwarding_class, None);
        assert_eq!(map.classes[3].lsp_next_hops, ["lsp-default"]);
    }

    #[test]
    fn reads_the_classification_overrides() {
        let policy = class_of_service(&juniper::parse_braces(EXTRA))
            .unwrap()
            .forwarding_policy
            .unwrap();
        assert_eq!(policy.classes.len(), 2);
        assert_eq!(policy.classes[0].name, "voice");
        assert_eq!(
            policy.classes[0].classification_override.as_deref(),
            Some("expedited-forwarding")
        );
        assert_eq!(policy.classes[1].classification_override, None);
    }

    #[test]
    fn no_forwarding_policy_is_none() {
        let cos = class_of_service(&juniper::parse_braces("class-of-service;\n")).unwrap();
        assert_eq!(cos.forwarding_policy, None);
    }
}