asterust-junos 0.5.2

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
//! `diffserv-te`
//! `protocols { mpls { diffserv-te { ... } } }`.
//!
//! # See also
//!
//! - [diffserv-te](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/diffserv-te-edit-protocols-mpls.html)
//! - [bandwidth-model](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/bandwidth-model-edit-protocols-mpls.html)
//! - [te-class-matrix](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/te-class-matrix-edit-protocols-mpls.html)
//! - [DiffServ-Aware Traffic Engineering Configuration](https://networkingdocs.hpe.com/documentation/us/en/software/junos/mpls/topics/topic-map/diffserv-aware-traffic-engineering-configuraion.html)

use crate::{active_children, arg_of, args_of, child_block, value_after};
use asterust::config::ConfigLine;

/// A `traffic-class` of a TE class: a class type and its priority.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct MplsTrafficClass {
    /// The class type, e.g. `ct0`.
    pub class_type: String,
    pub priority: Option<String>,
}

/// A `te <number>` entry of the `te-class-matrix`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct MplsTeClass {
    /// The number, as in `te 0` or `te0`.
    pub te: String,
    pub priority: Option<String>,
    pub traffic_classes: Vec<MplsTrafficClass>,
}

/// The `diffserv-te` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct MplsDiffservTe {
    /// `extended-mam`, `mam` or `rdm`.
    pub bandwidth_model: Option<String>,
    pub te_class_matrix: Vec<MplsTeClass>,
}

/// `ct <number> priority <n>` or `ct<number> priority <n>`.
fn parse_traffic_class(statement: &str) -> Option<MplsTrafficClass> {
    let words: Vec<&str> = statement.split_whitespace().collect();
    let class_type = if let Some(position) = words.iter().position(|w| *w == "ct") {
        format!("ct{}", words.get(position + 1)?)
    } else {
        (*words.iter().find(|w| w.starts_with("ct"))?).to_string()
    };
    Some(MplsTrafficClass {
        class_type,
        priority: value_after(&words, "priority"),
    })
}

/// `te` is the text after `te`: `0`, or `0 traffic-class ct1 priority 4` for the inline form.
fn parse_te_class(te: &str, entry: &ConfigLine) -> MplsTeClass {
    let (number, inline) = te.split_once(char::is_whitespace).unwrap_or((te, ""));
    let mut classes: Vec<MplsTrafficClass> = args_of(entry, "traffic-class")
        .into_iter()
        .filter_map(parse_traffic_class)
        .collect();
    if let Some(statement) = inline.trim().strip_prefix("traffic-class") {
        classes.extend(parse_traffic_class(statement));
    }
    if let Some(block) = child_block(entry, "traffic-class") {
        classes.extend(active_children(block).filter_map(|c| parse_traffic_class(&c.text)));
    }
    MplsTeClass {
        te: number.to_string(),
        priority: arg_of(entry, "priority").map(str::to_string),
        traffic_classes: classes,
    }
}

pub(super) fn parse_diffserv_te(mpls: &ConfigLine) -> Option<MplsDiffservTe> {
    let diffserv = child_block(mpls, "diffserv-te")?;
    let model = child_block(diffserv, "bandwidth-model");
    Some(MplsDiffservTe {
        bandwidth_model: model.and_then(|block| {
            ["extended-mam", "mam", "rdm"]
                .into_iter()
                .find(|name| active_children(block).any(|c| c.text == *name))
                .map(str::to_string)
        }),
        te_class_matrix: child_block(diffserv, "te-class-matrix")
            .map(|matrix| {
                active_children(matrix)
                    .filter_map(|entry| {
                        let te = entry.text.strip_prefix("te")?.trim();
                        Some(parse_te_class(te, entry))
                    })
                    .collect()
            })
            .unwrap_or_default(),
    })
}

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

    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
    const CONFIG: &str = r#"
protocols {
    mpls {
        diffserv-te {
            bandwidth-model {
                rdm;
            }
            te-class-matrix {
                te 0 {
                    priority 7;
                    traffic-class {
                        ct 0 priority 7;
                    }
                }
                te1 {
                    traffic-class ct1 priority 5;
                    traffic-class ct2 priority 4;
                }
            }
        }
    }
}
"#;

    #[test]
    fn reads_the_bandwidth_model_and_te_classes() {
        let diffserv = mpls(&juniper::parse_braces(CONFIG)).unwrap().diffserv_te.unwrap();
        assert_eq!(diffserv.bandwidth_model.as_deref(), Some("rdm"));
        assert_eq!(diffserv.te_class_matrix.len(), 2);

        let first = &diffserv.te_class_matrix[0];
        assert_eq!(first.te, "0");
        assert_eq!(first.priority.as_deref(), Some("7"));
        assert_eq!(first.traffic_classes.len(), 1);
        assert_eq!(first.traffic_classes[0].class_type, "ct0");
        assert_eq!(first.traffic_classes[0].priority.as_deref(), Some("7"));

        let second = &diffserv.te_class_matrix[1];
        assert_eq!(second.te, "1");
        assert_eq!(second.priority, None);
        let types: Vec<_> = second.traffic_classes.iter().map(|c| c.class_type.as_str()).collect();
        assert_eq!(types, ["ct1", "ct2"]);
        assert_eq!(second.traffic_classes[1].priority.as_deref(), Some("4"));
    }

    #[test]
    fn a_bare_diffserv_te_block_has_nothing_set() {
        let diffserv = mpls(&juniper::parse_braces(
            "protocols {\n    mpls {\n        diffserv-te;\n    }\n}\n",
        ))
        .unwrap()
        .diffserv_te
        .unwrap();
        assert_eq!(diffserv, Default::default());
    }

    // The `te-class-matrix` example of DiffServ-Aware Traffic Engineering Configuration (MPLS Applications User Guide),
    // under `protocols mpls diffserv-te`; see the README "Sources".
    const DOC_TE_CLASS: &str = r#"
protocols {
    mpls {
        diffserv-te {
            te-class-matrix {
                te0 traffic-class ct1 priority 4;
            }
        }
    }
}
"#;

    #[test]
    fn reads_the_guide_inline_te_class() {
        let diffserv = mpls(&juniper::parse_braces(DOC_TE_CLASS)).unwrap().diffserv_te.unwrap();
        assert_eq!(diffserv.bandwidth_model, None);
        assert_eq!(diffserv.te_class_matrix.len(), 1);
        let class = &diffserv.te_class_matrix[0];
        assert_eq!(class.te, "0");
        assert_eq!(class.traffic_classes.len(), 1);
        assert_eq!(class.traffic_classes[0].class_type, "ct1");
        assert_eq!(class.traffic_classes[0].priority.as_deref(), Some("4"));
    }
}