asterust-junos 0.4.4

Typed Juniper JunOS config views (interfaces, OSPF, BGP, IS-IS, routing instances, policy options, firewall filters, system) extracted from an asterust config tree.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! `interfaces`
//! `class-of-service { interfaces { <interface> { ... } interface-set <name> { ... } } }`.
//!
//! The `rewrite-value`, `monitoring-profile` and ACX `*-classifier` and `*-rewrite` statements are not extracted.
//!
//! # See also
//!
//! - [interfaces (class-of-service)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/interfaces-edit-cos.html)
//! - [unit (class-of-service)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/unit-edit-cos.html)
//! - [interface-set (class-of-service)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/interface-set-edit-cos.html)
//! - [Example: Configure and Apply Custom BA Classifiers](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cos-security-devices/cos/topics/example/cos-behavior-aggregate-classifier-configuring-security.html)
//! - [Example: Controlling Remaining Traffic](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cos-security-devices/topics/example/cos-control-remaining-traffic-security-configuring.html)
//! - [Example: Configuring a Four-Level Scheduler Hierarchy](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cos-security-devices/topics/example/cos-hierarchical-scheduler-security-configuring.html)

use super::platform::parse_multi_destination;
use super::scheduler::{rate_of, SchedulerRate};
use super::words;
use crate::{active_children, arg_of, child_block, has_leaf, named_children, value_after};
use asterust::config::ConfigLine;

/// A classifier or rewrite rule applied to an interface or unit, such as `dscp ba-classifier;`,
/// `ieee-802.1 dot1p vlan-tag outer;` or `exp mpls-out protocol mpls-any;`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AppliedMapping {
    /// `dscp`, `dscp-ipv6`, `exp`, `exp-push-push-push`, `exp-swap-push-push`, `ieee-802.1`, `inet-precedence`, ...
    pub kind: String,
    /// The name of the classifier or rewrite rule, or `default`.
    pub name: String,
    /// `mpls`, `inet` or `all`.
    pub family: Option<String>,
    pub protocol: Option<String>,
    pub vlan_tag: Option<String>,
}

/// A traffic-control profile applied with `output-traffic-control-profile <name> [shared-instance <name>]`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AppliedProfile {
    pub name: String,
    pub shared_instance: Option<String>,
}

/// The statements that an interface and a logical unit have in common.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CosSettings {
    pub classifiers: Vec<AppliedMapping>,
    pub rewrite_rules: Vec<AppliedMapping>,
    pub forwarding_class: Option<String>,
    pub fragmentation_map: Option<String>,
    pub scheduler_map: Option<String>,
    pub scheduler_map_chassis: Option<String>,
    pub input_scheduler_map: Option<String>,
    pub shaping_rate: Option<SchedulerRate>,
    pub input_shaping_rate: Option<SchedulerRate>,
    pub input_traffic_control_profile: Option<AppliedProfile>,
    pub input_traffic_control_profile_remaining: Option<AppliedProfile>,
    pub output_traffic_control_profile: Option<AppliedProfile>,
    pub output_traffic_control_profile_remaining: Option<AppliedProfile>,
    pub per_session_scheduler: bool,
    pub policy_map: Option<String>,
    pub policy_map_marking: bool,
    pub hierarchical_scheduler: bool,
    /// `replicate` or `scale`.
    pub member_link_scheduler: Option<String>,
    pub congestion_notification_profile: Option<String>,
    pub dedicated_buffer_profile: Option<String>,
    pub virtual_channel_group: Option<String>,
    pub dynamic_threshold_profile: Option<String>,
    /// `drop-congestion-notification`: generate DCN-trimmed packets in case of congestion.
    pub drop_congestion_notification: bool,
    /// The `classifiers` of `multi-destination`.
    pub multi_destination_classifiers: Vec<AppliedMapping>,
}

/// A `unit <number>` of a class-of-service interface.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CosUnit {
    pub number: String,
    pub settings: CosSettings,
}

/// A `forwarding-class-set <name>` or `slice <name>` of an interface, with its traffic-control profile.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CosBinding {
    pub name: String,
    pub output_traffic_control_profile: Option<AppliedProfile>,
}

/// An interface of `class-of-service interfaces`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CosInterface {
    pub name: String,
    pub settings: CosSettings,
    pub forwarding_class_sets: Vec<CosBinding>,
    pub slices: Vec<CosBinding>,
    pub units: Vec<CosUnit>,
}

/// An `interface-set <name>` of `class-of-service interfaces`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CosInterfaceSet {
    pub name: String,
    /// `proportional <value>` or `equal`.
    pub excess_bandwidth_share: Option<String>,
    pub internal_node: bool,
    pub output_traffic_control_profile: Option<AppliedProfile>,
    pub output_traffic_control_profile_remaining: Option<AppliedProfile>,
}

pub(super) fn parse_mappings(line: &ConfigLine, block: &str) -> Vec<AppliedMapping> {
    let Some(block) = child_block(line, block) else {
        return Vec::new();
    };
    active_children(block)
        .filter_map(|statement| {
            let words = words(statement, 0);
            let (kind, name) = (words.first()?, words.get(1)?);
            Some(AppliedMapping {
                kind: kind.to_string(),
                name: name.to_string(),
                family: value_after(&words, "family"),
                protocol: value_after(&words, "protocol"),
                vlan_tag: value_after(&words, "vlan-tag"),
            })
        })
        .collect()
}

fn parse_profile(line: &ConfigLine, keyword: &str) -> Option<AppliedProfile> {
    let words: Vec<&str> = arg_of(line, keyword)?.split_whitespace().collect();
    Some(AppliedProfile {
        name: words.first()?.to_string(),
        shared_instance: value_after(&words, "shared-instance"),
    })
}

fn parse_settings(line: &ConfigLine) -> CosSettings {
    let field = |keyword: &str| arg_of(line, keyword).map(str::to_string);
    CosSettings {
        classifiers: parse_mappings(line, "classifiers"),
        rewrite_rules: parse_mappings(line, "rewrite-rules"),
        forwarding_class: field("forwarding-class"),
        fragmentation_map: field("fragmentation-map"),
        scheduler_map: field("scheduler-map"),
        scheduler_map_chassis: field("scheduler-map-chassis"),
        input_scheduler_map: field("input-scheduler-map"),
        shaping_rate: rate_of(line, "shaping-rate"),
        input_shaping_rate: rate_of(line, "input-shaping-rate"),
        input_traffic_control_profile: parse_profile(line, "input-traffic-control-profile"),
        input_traffic_control_profile_remaining: parse_profile(line, "input-traffic-control-profile-remaining"),
        output_traffic_control_profile: parse_profile(line, "output-traffic-control-profile"),
        output_traffic_control_profile_remaining: parse_profile(line, "output-traffic-control-profile-remaining"),
        per_session_scheduler: has_leaf(line, "per-session-scheduler"),
        policy_map: field("policy-map"),
        policy_map_marking: has_leaf(line, "policy-map-marking"),
        hierarchical_scheduler: has_leaf(line, "hierarchical-scheduler"),
        member_link_scheduler: field("member-link-scheduler"),
        congestion_notification_profile: field("congestion-notification-profile"),
        dedicated_buffer_profile: field("dedicated-buffer-profile"),
        virtual_channel_group: field("virtual-channel-group"),
        dynamic_threshold_profile: field("dynamic-threshold-profile"),
        drop_congestion_notification: has_leaf(line, "drop-congestion-notification"),
        multi_destination_classifiers: parse_multi_destination(line),
    }
}

fn parse_bindings(interface: &ConfigLine, keyword: &str) -> Vec<CosBinding> {
    named_children(interface, keyword)
        .map(|(name, binding)| CosBinding {
            name: name.to_string(),
            output_traffic_control_profile: parse_profile(binding, "output-traffic-control-profile"),
        })
        .collect()
}

fn parse_interface(name: &str, interface: &ConfigLine) -> CosInterface {
    CosInterface {
        name: name.to_string(),
        settings: parse_settings(interface),
        forwarding_class_sets: parse_bindings(interface, "forwarding-class-set"),
        slices: parse_bindings(interface, "slice"),
        units: named_children(interface, "unit")
            .map(|(number, unit)| CosUnit {
                number: number.to_string(),
                settings: parse_settings(unit),
            })
            .collect(),
    }
}

fn parse_interface_set(name: &str, set: &ConfigLine) -> CosInterfaceSet {
    let share = crate::statement_words(set, "excess-bandwidth-share").map(|words| words.join(" "));
    CosInterfaceSet {
        name: name.to_string(),
        excess_bandwidth_share: share,
        internal_node: has_leaf(set, "internal-node"),
        output_traffic_control_profile: parse_profile(set, "output-traffic-control-profile"),
        output_traffic_control_profile_remaining: parse_profile(set, "output-traffic-control-profile-remaining"),
    }
}

pub(super) fn parse_interfaces(cos: &ConfigLine) -> (Vec<CosInterface>, Vec<CosInterfaceSet>) {
    let Some(block) = child_block(cos, "interfaces") else {
        return (Vec::new(), Vec::new());
    };
    let mut interfaces = Vec::new();
    let mut sets = Vec::new();
    for child in active_children(block) {
        if let Some(name) = child.arg("interface-set") {
            sets.push(parse_interface_set(
                name.split_whitespace().next().unwrap_or(name),
                child,
            ));
        } else if let Some(name) = child.text.split_whitespace().next() {
            interfaces.push(parse_interface(name, child));
        }
    }
    (interfaces, sets)
}

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

    // The `class-of-service interfaces` of the BA classifier, IPv6 rewrite rule, scheduler map, hierarchical scheduler
    // and remaining traffic examples (Class of Service User Guide for Security Devices), wrapped in `class-of-service`
    // and shortened; see the README "Sources".
    const DOC_UNITS: &str = r#"
class-of-service {
    interfaces {
        ge-0/0/0 {
            unit 0 {
                classifiers {
                    dscp ba-classifier;
                }
                rewrite-rules {
                    dscp-ipv6 rewrite-ipv6-dscps;
                }
                scheduler-map diffserv-cos-map;
            }
        }
        ge-0/0/1 {
            scheduler-map be-map;
        }
    }
}
"#;

    const DOC_HIERARCHY: &str = r#"
class-of-service {
    interfaces {
        ge-1/0/0 {
            output-traffic-control-profile tcp-500m-shaping-rate;
            unit 0 {
                output-traffic-control-profile tcp-cvlan0;
            }
            unit 1 {
                output-traffic-control-profile tcp-cvlan1;
            }
        }
        interface-set svlan0 {
            output-traffic-control-profile tcp-svlan0;
        }
        interface-set svlan1 {
            output-traffic-control-profile tcp-svlan1;
            output-traffic-control-profile-remaining tcp-svlan1-remaining;
        }
    }
}
"#;

    // Not from documentation: written from the CLI Reference. See the README "Sources".
    const EXTRA: &str = r#"
class-of-service {
    interfaces {
        xe-0/0/0 {
            hierarchical-scheduler;
            shaping-rate 5g burst-size 128k;
            input-shaping-rate percent 50;
            input-scheduler-map in-map;
            forwarding-class-set VOICE {
                output-traffic-control-profile tcp-voice;
            }
            slice A {
                output-traffic-control-profile tcp-a shared-instance si1;
            }
            member-link-scheduler scale;
            congestion-notification-profile cnp1;
            dedicated-buffer-profile dbp1;
            classifiers {
                ieee-802.1 dot1p vlan-tag outer;
            }
            rewrite-rules {
                exp mpls-out protocol mpls-any;
                exp-push-push-push default;
            }
            unit 100 {
                forwarding-class be;
                fragmentation-map fm1;
                input-traffic-control-profile tcp-in shared-instance in1;
                per-session-scheduler;
                policy-map pm1;
                policy-map-marking;
                classifiers {
                    dscp default family mpls;
                }
            }
        }
        interface-set EDGE {
            excess-bandwidth-share proportional 100;
            internal-node;
        }
        interface-set SPLIT {
            excess-bandwidth-share equal;
        }
    }
}
"#;

    fn cos(text: &str) -> crate::class_of_service::ClassOfService {
        class_of_service(&juniper::parse_braces(text)).unwrap()
    }

    #[test]
    fn reads_the_guide_units() {
        let cos = cos(DOC_UNITS);
        assert_eq!(cos.interfaces.len(), 2);
        let first = &cos.interfaces[0];
        assert_eq!(first.name, "ge-0/0/0");
        assert_eq!(first.units.len(), 1);
        let unit = &first.units[0];
        assert_eq!(unit.number, "0");
        assert_eq!(unit.settings.classifiers[0].kind, "dscp");
        assert_eq!(unit.settings.classifiers[0].name, "ba-classifier");
        assert_eq!(unit.settings.rewrite_rules[0].kind, "dscp-ipv6");
        assert_eq!(unit.settings.rewrite_rules[0].name, "rewrite-ipv6-dscps");
        assert_eq!(unit.settings.scheduler_map.as_deref(), Some("diffserv-cos-map"));
        assert_eq!(cos.interfaces[1].settings.scheduler_map.as_deref(), Some("be-map"));
        assert!(cos.interfaces[1].units.is_empty());
    }

    #[test]
    fn reads_the_guide_hierarchy() {
        let cos = cos(DOC_HIERARCHY);
        assert_eq!(cos.interfaces.len(), 1);
        let port = &cos.interfaces[0];
        let profile = port.settings.output_traffic_control_profile.as_ref().unwrap();
        assert_eq!(profile.name, "tcp-500m-shaping-rate");
        assert_eq!(profile.shared_instance, None);
        assert_eq!(port.units.len(), 2);
        assert_eq!(
            port.units[1]
                .settings
                .output_traffic_control_profile
                .as_ref()
                .unwrap()
                .name,
            "tcp-cvlan1"
        );
        assert_eq!(cos.interface_sets.len(), 2);
        assert_eq!(cos.interface_sets[0].name, "svlan0");
        assert_eq!(
            cos.interface_sets[0]
                .output_traffic_control_profile
                .as_ref()
                .unwrap()
                .name,
            "tcp-svlan0"
        );
        assert_eq!(cos.interface_sets[0].output_traffic_control_profile_remaining, None);
        assert_eq!(
            cos.interface_sets[1]
                .output_traffic_control_profile_remaining
                .as_ref()
                .unwrap()
                .name,
            "tcp-svlan1-remaining"
        );
    }

    #[test]
    fn reads_the_interface_options() {
        let interface = &cos(EXTRA).interfaces[0];
        let settings = &interface.settings;
        assert!(settings.hierarchical_scheduler);
        let shaping = settings.shaping_rate.as_ref().unwrap();
        assert_eq!(shaping.value.as_deref(), Some("5g"));
        assert_eq!(shaping.burst_size.as_deref(), Some("128k"));
        let input = settings.input_shaping_rate.as_ref().unwrap();
        assert_eq!(input.mode.as_deref(), Some("percent"));
        assert_eq!(settings.input_scheduler_map.as_deref(), Some("in-map"));
        assert_eq!(settings.member_link_scheduler.as_deref(), Some("scale"));
        assert_eq!(settings.congestion_notification_profile.as_deref(), Some("cnp1"));
        assert_eq!(settings.dedicated_buffer_profile.as_deref(), Some("dbp1"));
        assert_eq!(interface.forwarding_class_sets[0].name, "VOICE");
        assert_eq!(
            interface.forwarding_class_sets[0]
                .output_traffic_control_profile
                .as_ref()
                .unwrap()
                .name,
            "tcp-voice"
        );
        let slice = interface.slices[0].output_traffic_control_profile.as_ref().unwrap();
        assert_eq!(slice.name, "tcp-a");
        assert_eq!(slice.shared_instance.as_deref(), Some("si1"));
    }

    #[test]
    fn reads_vlan_tags_protocols_and_families() {
        let interface = &cos(EXTRA).interfaces[0];
        let classifier = &interface.settings.classifiers[0];
        assert_eq!(classifier.kind, "ieee-802.1");
        assert_eq!(classifier.vlan_tag.as_deref(), Some("outer"));
        assert_eq!(
            interface.settings.rewrite_rules[0].protocol.as_deref(),
            Some("mpls-any")
        );
        assert_eq!(interface.settings.rewrite_rules[1].kind, "exp-push-push-push");
        assert_eq!(interface.settings.rewrite_rules[1].name, "default");
        let unit = &interface.units[0];
        assert_eq!(unit.settings.classifiers[0].name, "default");
        assert_eq!(unit.settings.classifiers[0].family.as_deref(), Some("mpls"));
    }

    #[test]
    fn reads_the_unit_options() {
        let unit = &cos(EXTRA).interfaces[0].units[0];
        assert_eq!(unit.number, "100");
        assert_eq!(unit.settings.forwarding_class.as_deref(), Some("be"));
        assert_eq!(unit.settings.fragmentation_map.as_deref(), Some("fm1"));
        let profile = unit.settings.input_traffic_control_profile.as_ref().unwrap();
        assert_eq!(profile.name, "tcp-in");
        assert_eq!(profile.shared_instance.as_deref(), Some("in1"));
        assert!(unit.settings.per_session_scheduler);
        assert_eq!(unit.settings.policy_map.as_deref(), Some("pm1"));
        assert!(unit.settings.policy_map_marking);
        assert!(!unit.settings.hierarchical_scheduler);
    }

    #[test]
    fn reads_the_interface_set_options() {
        let sets = cos(EXTRA).interface_sets;
        assert_eq!(sets.len(), 2);
        assert_eq!(sets[0].name, "EDGE");
        assert_eq!(sets[0].excess_bandwidth_share.as_deref(), Some("proportional 100"));
        assert!(sets[0].internal_node);
        assert_eq!(sets[1].excess_bandwidth_share.as_deref(), Some("equal"));
        assert!(!sets[1].internal_node);
    }
}