Skip to main content

asterust_junos/routing_options/
flex_algorithm.rs

1//! `flex-algorithm`
2//! `routing-options { flex-algorithm <id> { color <color>; definition { ... } } }`.
3//!
4//! # See also
5//!
6//! - [flex-algorithm](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/flex-algorithm-edit-routing-options.html)
7//! - [definition](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/definition-edit-routing-options-flex-algorithm.html)
8//! - [flex-algorithm (Protocols OSPF)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/flex-algorithm-ospf-edit-routing-options.html)
9//! - [definition (Protocols OSPF)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/definition-ospf-edit-routing-options.html)
10//! - [Configuring Flexible Algorithm for Segment Routing](https://networkingdocs.hpe.com/documentation/us/en/software/junos/is-is/segment-routing/topics/task/isis-configuring-flex-algo-sr.html)
11//! - [Flexible Algorithms in IS-IS for Segment Routing Traffic Engineering](https://networkingdocs.hpe.com/documentation/us/en/software/junos/is-is/topics/topic-map/infocus-isis-flex-algo-sr.html)
12//! - [How to Configure Flexible Algorithms in OSPF for Segment Routing Traffic Engineering](https://networkingdocs.hpe.com/documentation/us/en/software/junos/ospf/topics/topic-map/ospf-flex-algo-sr.html)
13
14use crate::{active_children, arg_of, has_leaf, list_values, named_children, split_keyword, split_name};
15use asterust::config::ConfigLine;
16
17/// A `flex-algorithm <id>` of `routing-options`, a flexible algorithm definition (FAD) for IS-IS or OSPFv2.
18#[derive(Clone, Debug, PartialEq, Eq)]
19#[non_exhaustive]
20pub struct FlexAlgorithm {
21    /// 128 through 255.
22    pub id: String,
23    /// The BGP color associated with the algorithm.
24    pub color: Option<String>,
25    pub use_transport_class: bool,
26    pub definition: Option<FlexAlgorithmDefinition>,
27}
28
29/// The `definition` of a [`FlexAlgorithm`]. The `exclude-srlg` and `use-flex-algorithm-prefix-metric` options are
30/// only documented for IS-IS.
31#[derive(Clone, Debug, Default, PartialEq, Eq)]
32#[non_exhaustive]
33pub struct FlexAlgorithmDefinition {
34    pub spf: bool,
35    pub strict_spf: bool,
36    /// `delay-metric`, `igp-metric` or `te-metric`.
37    pub metric_type: Option<String>,
38    /// 0 through 255.
39    pub priority: Option<String>,
40    /// Admin group names from `admin-group include-any`.
41    pub admin_group_include_any: Vec<String>,
42    pub admin_group_include_all: Vec<String>,
43    pub admin_group_exclude: Vec<String>,
44    pub exclude_srlg: Vec<String>,
45    pub use_flex_algorithm_prefix_metric: bool,
46}
47
48pub(super) fn parse_flex_algorithms(root: &ConfigLine) -> Vec<FlexAlgorithm> {
49    named_children(root, "flex-algorithm")
50        .map(|(arg, algorithm)| {
51            let (id, rest) = split_name(arg);
52            FlexAlgorithm {
53                id: id.to_string(),
54                color: arg_of(algorithm, "color").map(str::to_string),
55                use_transport_class: rest.split_whitespace().any(|word| word == "use-transport-class")
56                    || has_leaf(algorithm, "use-transport-class"),
57                definition: parse_definition(algorithm),
58            }
59        })
60        .collect()
61}
62
63/// Reads the `definition` block, including a collapsed `definition spf;` and a nested `admin-group { ... }`.
64fn parse_definition(algorithm: &ConfigLine) -> Option<FlexAlgorithmDefinition> {
65    let node =
66        active_children(algorithm).find(|child| child.text == "definition" || child.arg("definition").is_some())?;
67    let mut statements: Vec<String> = Vec::new();
68    if let Some(inline) = node.arg("definition") {
69        statements.push(inline.to_string());
70    }
71    for child in active_children(node) {
72        let nested: Vec<_> = active_children(child).collect();
73        if nested.is_empty() {
74            statements.push(child.text.clone());
75        } else {
76            statements.extend(nested.iter().map(|inner| format!("{} {}", child.text, inner.text)));
77        }
78    }
79    let mut definition = FlexAlgorithmDefinition::default();
80    for statement in &statements {
81        let (keyword, rest) = split_keyword(statement);
82        let first = rest.split_whitespace().next().map(str::to_string);
83        match keyword {
84            "spf" => definition.spf = true,
85            "strict-spf" => definition.strict_spf = true,
86            "metric-type" => definition.metric_type = first,
87            "priority" => definition.priority = first,
88            "use-flex-algorithm-prefix-metric" => definition.use_flex_algorithm_prefix_metric = true,
89            "exclude-srlg" => definition.exclude_srlg.extend(list_values(rest)),
90            "admin-group" => {
91                let (kind, names) = split_keyword(rest);
92                let target = match kind {
93                    "include-any" => &mut definition.admin_group_include_any,
94                    "include-all" => &mut definition.admin_group_include_all,
95                    "exclude" => &mut definition.admin_group_exclude,
96                    _ => continue,
97                };
98                target.extend(list_values(names));
99            }
100            _ => {}
101        }
102    }
103    Some(definition)
104}
105
106#[cfg(test)]
107mod tests {
108    use crate::routing_options::routing_options;
109    use asterust::config::juniper;
110
111    // Adapted from "How to Configure Flexible Algorithms in OSPF for Segment Routing Traffic Engineering" (OSPF User
112    // Guide), Device R0 `show routing-options`, plus entries written from the CLI Reference; see the README "Sources".
113    const CONFIG: &str = r#"
114routing-options {
115    router-id 192.168.255.10;
116    flex-algorithm 128 {
117        definition {
118            metric-type igp-metric;
119            spf;
120            admin-group include-any RED;
121        }
122    }
123    flex-algorithm 129 {
124        definition {
125            metric-type te-metric;
126            spf;
127            admin-group include-all [ GREEN BLUE ];
128        }
129    }
130    flex-algorithm 130 {
131        color 1300;
132        use-transport-class;
133        definition {
134            strict-spf;
135            metric-type delay-metric;
136            priority 200;
137            exclude-srlg [ SRLG-A SRLG-B ];
138            use-flex-algorithm-prefix-metric;
139            admin-group {
140                exclude RED;
141            }
142        }
143    }
144    flex-algorithm 131 {
145        definition;
146    }
147    flex-algorithm 132;
148}
149"#;
150
151    #[test]
152    fn reads_the_guide_definitions() {
153        let options = routing_options(&juniper::parse_braces(CONFIG)).unwrap();
154        assert_eq!(options.flex_algorithms.len(), 5);
155
156        let first = &options.flex_algorithms[0];
157        assert_eq!(first.id, "128");
158        let definition = first.definition.as_ref().unwrap();
159        assert_eq!(definition.metric_type.as_deref(), Some("igp-metric"));
160        assert!(definition.spf);
161        assert!(!definition.strict_spf);
162        assert_eq!(definition.admin_group_include_any, ["RED"]);
163
164        let second = options.flex_algorithms[1].definition.as_ref().unwrap();
165        assert_eq!(second.metric_type.as_deref(), Some("te-metric"));
166        assert_eq!(second.admin_group_include_all, ["GREEN", "BLUE"]);
167        assert!(second.admin_group_include_any.is_empty());
168    }
169
170    #[test]
171    fn reads_the_remaining_options() {
172        let options = routing_options(&juniper::parse_braces(CONFIG)).unwrap();
173        let algorithm = &options.flex_algorithms[2];
174        assert_eq!(algorithm.color.as_deref(), Some("1300"));
175        assert!(algorithm.use_transport_class);
176        let definition = algorithm.definition.as_ref().unwrap();
177        assert!(definition.strict_spf);
178        assert_eq!(definition.metric_type.as_deref(), Some("delay-metric"));
179        assert_eq!(definition.priority.as_deref(), Some("200"));
180        assert_eq!(definition.exclude_srlg, ["SRLG-A", "SRLG-B"]);
181        assert!(definition.use_flex_algorithm_prefix_metric);
182        assert_eq!(definition.admin_group_exclude, ["RED"]);
183    }
184
185    #[test]
186    fn reads_a_bare_definition_and_a_bare_algorithm() {
187        let options = routing_options(&juniper::parse_braces(CONFIG)).unwrap();
188        let bare_definition = &options.flex_algorithms[3];
189        assert_eq!(bare_definition.id, "131");
190        assert_eq!(bare_definition.definition, Some(Default::default()));
191
192        let bare = &options.flex_algorithms[4];
193        assert_eq!(bare.id, "132");
194        assert_eq!(bare.definition, None);
195        assert_eq!(bare.color, None);
196    }
197}