Skip to main content

asterust_junos/class_of_service/
application_traffic_control.rs

1//! `application-traffic-control`
2//! `class-of-service { application-traffic-control { rate-limiters { ... } rule-sets <name> { ... } } }`.
3//!
4//! # See also
5//!
6//! - [application-traffic-control](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/class-of-service-edit-application-traffic-control.html)
7//! - [rate-limiters](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/class-of-service-edit-rate-limiters.html)
8
9use super::words;
10use crate::{active_children, arg_of, args_of, child_block, has_leaf, list_values, named_children, value_after};
11use asterust::config::ConfigLine;
12
13/// A `rate-limiters` entry.
14#[derive(Clone, Debug, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct RateLimiter {
17    pub name: String,
18    /// Kilobits per second.
19    pub bandwidth_limit: Option<String>,
20    /// Bytes.
21    pub burst_size_limit: Option<String>,
22}
23
24/// The `rate-limit` action of a rule.
25#[derive(Clone, Debug, Default, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct RuleRateLimit {
28    pub loss_priority_high: bool,
29    pub client_to_server: Option<String>,
30    pub server_to_client: Option<String>,
31}
32
33/// A `rule <name>` of a rule set.
34#[derive(Clone, Debug, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct AppQosRule {
37    pub name: String,
38    /// The `application` names of `match`.
39    pub applications: Vec<String>,
40    pub application_groups: Vec<String>,
41    /// `application-any`, `application-known` and `application-unknown`, as written.
42    pub application_flags: Vec<String>,
43    pub dscp_code_point: Option<String>,
44    pub forwarding_class: Option<String>,
45    pub log: bool,
46    pub loss_priority: Vec<String>,
47    pub rate_limit: Option<RuleRateLimit>,
48}
49
50/// A `rule-sets` entry.
51#[derive(Clone, Debug, PartialEq, Eq)]
52#[non_exhaustive]
53pub struct AppQosRuleSet {
54    pub name: String,
55    pub rules: Vec<AppQosRule>,
56}
57
58/// The `application-traffic-control` block.
59#[derive(Clone, Debug, Default, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct ApplicationTrafficControl {
62    pub rate_limiters: Vec<RateLimiter>,
63    pub rule_sets: Vec<AppQosRuleSet>,
64}
65
66fn parse_rule(name: &str, rule: &ConfigLine) -> AppQosRule {
67    let matches = child_block(rule, "match");
68    let then = child_block(rule, "then");
69    let list = |block: Option<&ConfigLine>, keyword: &str| -> Vec<String> {
70        block
71            .map(|block| args_of(block, keyword).into_iter().map(str::to_string).collect())
72            .unwrap_or_default()
73    };
74    AppQosRule {
75        name: name.to_string(),
76        applications: list(matches, "application"),
77        application_groups: list(matches, "application-group"),
78        application_flags: matches
79            .map(|block| {
80                active_children(block)
81                    .map(|child| child.text.as_str())
82                    .filter(|text| matches!(*text, "application-any" | "application-known" | "application-unknown"))
83                    .map(str::to_string)
84                    .collect()
85            })
86            .unwrap_or_default(),
87        dscp_code_point: then
88            .and_then(|block| arg_of(block, "dscp-code-point"))
89            .map(str::to_string),
90        forwarding_class: then
91            .and_then(|block| arg_of(block, "forwarding-class"))
92            .map(str::to_string),
93        log: then.is_some_and(|block| has_leaf(block, "log")),
94        loss_priority: then
95            .and_then(|block| arg_of(block, "loss-priority"))
96            .map(list_values)
97            .unwrap_or_default(),
98        rate_limit: then.and_then(|block| child_block(block, "rate-limit")).map(|limit| {
99            let words = words(limit, 0);
100            RuleRateLimit {
101                loss_priority_high: has_leaf(limit, "loss-priority-high"),
102                client_to_server: value_after(&words, "client-to-server"),
103                server_to_client: value_after(&words, "server-to-client"),
104            }
105        }),
106    }
107}
108
109pub(super) fn parse_application_traffic_control(cos: &ConfigLine) -> Option<ApplicationTrafficControl> {
110    let control = child_block(cos, "application-traffic-control")?;
111    Some(ApplicationTrafficControl {
112        rate_limiters: child_block(control, "rate-limiters")
113            .map(|block| {
114                active_children(block)
115                    .filter_map(|limiter| {
116                        Some(RateLimiter {
117                            name: limiter.text.split_whitespace().next()?.to_string(),
118                            bandwidth_limit: arg_of(limiter, "bandwidth-limit").map(str::to_string),
119                            burst_size_limit: arg_of(limiter, "burst-size-limit").map(str::to_string),
120                        })
121                    })
122                    .collect()
123            })
124            .unwrap_or_default(),
125        rule_sets: named_children(control, "rule-sets")
126            .map(|(name, set)| AppQosRuleSet {
127                name: name.to_string(),
128                rules: named_children(set, "rule")
129                    .map(|(rule, line)| parse_rule(rule, line))
130                    .collect(),
131            })
132            .collect(),
133    })
134}
135
136#[cfg(test)]
137mod tests {
138    use crate::class_of_service::class_of_service;
139    use asterust::config::juniper;
140
141    // Not from documentation: written from the CLI Reference. See the README "Sources".
142    const EXTRA: &str = r#"
143class-of-service {
144    application-traffic-control {
145        rate-limiters {
146            LIMIT-A {
147                bandwidth-limit 1000;
148                burst-size-limit 4000;
149            }
150        }
151        rule-sets VIDEO {
152            rule R1 {
153                match {
154                    application junos:youtube;
155                    application junos:netflix;
156                    application-group streaming;
157                    application-known;
158                }
159                then {
160                    dscp-code-point af11;
161                    forwarding-class assured-forwarding;
162                    log;
163                    loss-priority [ low medium-low ];
164                    rate-limit {
165                        loss-priority-high;
166                        client-to-server LIMIT-A;
167                        server-to-client LIMIT-A;
168                    }
169                }
170            }
171            rule R2 {
172                match {
173                    application-any;
174                }
175            }
176        }
177    }
178}
179"#;
180
181    #[test]
182    fn reads_the_rate_limiters() {
183        let control = class_of_service(&juniper::parse_braces(EXTRA))
184            .unwrap()
185            .application_traffic_control
186            .unwrap();
187        assert_eq!(control.rate_limiters.len(), 1);
188        assert_eq!(control.rate_limiters[0].name, "LIMIT-A");
189        assert_eq!(control.rate_limiters[0].bandwidth_limit.as_deref(), Some("1000"));
190        assert_eq!(control.rate_limiters[0].burst_size_limit.as_deref(), Some("4000"));
191    }
192
193    #[test]
194    fn reads_the_rule_sets() {
195        let control = class_of_service(&juniper::parse_braces(EXTRA))
196            .unwrap()
197            .application_traffic_control
198            .unwrap();
199        assert_eq!(control.rule_sets.len(), 1);
200        let set = &control.rule_sets[0];
201        assert_eq!(set.name, "VIDEO");
202        assert_eq!(set.rules.len(), 2);
203        let rule = &set.rules[0];
204        assert_eq!(rule.name, "R1");
205        assert_eq!(rule.applications, ["junos:youtube", "junos:netflix"]);
206        assert_eq!(rule.application_groups, ["streaming"]);
207        assert_eq!(rule.application_flags, ["application-known"]);
208        assert_eq!(rule.dscp_code_point.as_deref(), Some("af11"));
209        assert_eq!(rule.forwarding_class.as_deref(), Some("assured-forwarding"));
210        assert!(rule.log);
211        assert_eq!(rule.loss_priority, ["low", "medium-low"]);
212        let limit = rule.rate_limit.as_ref().unwrap();
213        assert!(limit.loss_priority_high);
214        assert_eq!(limit.client_to_server.as_deref(), Some("LIMIT-A"));
215        assert_eq!(limit.server_to_client.as_deref(), Some("LIMIT-A"));
216    }
217
218    #[test]
219    fn a_rule_without_actions_has_none() {
220        let control = class_of_service(&juniper::parse_braces(EXTRA))
221            .unwrap()
222            .application_traffic_control
223            .unwrap();
224        let rule = &control.rule_sets[0].rules[1];
225        assert_eq!(rule.application_flags, ["application-any"]);
226        assert!(rule.applications.is_empty());
227        assert!(!rule.log && rule.rate_limit.is_none() && rule.dscp_code_point.is_none());
228    }
229}