asterust-junos 0.4.2

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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! `mpls`
//! `protocols { mpls { ... } }`.
//!
//! This covers the router-wide options, the interfaces, the paths and the dynamic, static and container label-switched
//! paths. Segment routing statements, `egress-protection`, `lsp-external-controller`, `label-range`, `oam` and
//! `transit-lsp-association` are not extracted yet.
//!
//! # See also
//!
//! - [mpls (Protocols)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/mpls-edit-protocols.html)
//! - [admin-groups](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/admin-groups-edit-protocols-mpls.html)
//! - [explicit-null (Protocols MPLS)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/explicit-null-edit-protocols-mpls.html)
//! - [no-cspf](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-cspf-edit-protocols-mpls.html)
//! - [no-propagate-ttl](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-propagate-ttl-edit-protocols-mpls.html)
//! - [no-decrement-ttl](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-decrement-ttl-edit-protocols-mpls.html)
//! - [ipv6-tunneling](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/ipv6-tunneling-edit-protocols-mpls.html)
//! - [traffic-engineering (Protocols MPLS)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/traffic-engineering-edit-protocols-mpls.html)
//! - [optimize-timer (Protocols MPLS)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/optimize-timer-edit-protocols-mpls.html)
//! - [optimize-switchover-delay](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/optimize-switchover-delay-edit-protocols-mpls.html)
//! - [optimize-hold-dead-delay](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/optimize-hold-dead-delay-edit-protocols-mpls.html)
//! - [smart-optimize-timer](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/smart-optimize-timer-edit-protocols-mpls.html)
//! - [rsvp-error-hold-time](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/rsvp-error-hold-time-edit-protocols-mpls.html)
//! - [expand-loose-hop](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/expand-loose-hop-edit-protocols-mpls.html)
//! - [disable (Protocols MPLS)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/disable-edit-protocols-mpls.html)
//! - [path (Protocols MPLS)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/path-edit-protocols-mpls.html)
//! - [static-label-switched-path](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/static-label-switched-path-edit-protocols-mpls.html)
//! - [container-label-switched-path](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/container-label-switched-path-edit-protocols-mpls.html)
//! - [traceoptions (Protocols MPLS)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/traceoptions-edit-protocols-mpls.html)
//! - [class-of-service (Protocols MPLS)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/class-of-service-edit-protocols-mpls.html)
//! - [priority (Protocols MPLS)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/priority-edit-protocols-mpls.html)
//! - [hop-limit](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/hop-limit-edit-protocols-mpls.html)
//! - [preference (Protocols MPLS)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/preference-edit-protocols-mpls.html)
//! - [revert-timer](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/revert-timer-edit-protocols-mpls.html)
//! - [ultimate-hop-popping](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/ultimate-hop-popping-edit-protocols-mpls.html)
//! - [sensor-based-stats](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/sensor-based-stats-edit-protocols-mpls.html)
//! - [Basic MPLS Configuration](https://networkingdocs.hpe.com/documentation/us/en/software/junos/mpls/topics/topic-map/mpls-basic-configuration.html)

mod container_lsp;
mod diffserv_te;
mod interface;
mod label_switched_path;
mod log_updown;
mod lsp_path;
mod path;
mod path_mtu;
mod static_lsp;
mod statistics;

pub use container_lsp::MplsContainerLsp;
pub use diffserv_te::{MplsDiffservTe, MplsTeClass, MplsTrafficClass};
pub use interface::MplsInterface;
pub use label_switched_path::{MplsFastReroute, MplsLabelSwitchedPath};
pub use log_updown::MplsLogUpdown;
pub use lsp_path::{MplsAdminGroupConstraints, MplsLspPath};
pub use path::{MplsPath, MplsPathHop};
pub use path_mtu::MplsPathMtu;
pub use static_lsp::{MplsStaticBypass, MplsStaticIngress, MplsStaticLsp, MplsStaticNodeProtection, MplsStaticTransit};
pub use statistics::{MplsPollingProfile, MplsStatistics};

use super::traceoptions::{parse_traceoptions, Traceoptions};
use crate::{arg_of, child_block, has_leaf, named_children, split_name, top_level};
use asterust::config::{Config, ConfigLine};
use container_lsp::parse_container_lsp;
use diffserv_te::parse_diffserv_te;
use interface::parse_interface;
use label_switched_path::parse_label_switched_path;
use log_updown::parse_log_updown;
use path::parse_path;
use path_mtu::parse_path_mtu;
use static_lsp::parse_static_lsp;
use statistics::parse_statistics;

/// An `admin-groups` entry: a link color name and its bit.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct MplsAdminGroup {
    pub name: String,
    /// 0 through 31.
    pub value: String,
}

/// The `protocols mpls` configuration. Segment routing, `egress-protection`, `lsp-external-controller`, `label-range`,
/// `oam` and `transit-lsp-association` are not extracted.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Mpls {
    pub disable: bool,
    pub interfaces: Vec<MplsInterface>,
    pub admin_groups: Vec<MplsAdminGroup>,
    /// Advertise label 0 instead of implicit null to the egress router.
    pub explicit_null: bool,
    /// Disable constrained-path LSP computation.
    pub no_cspf: bool,
    pub no_propagate_ttl: bool,
    pub no_decrement_ttl: bool,
    pub ipv6_tunneling: bool,
    pub expand_loose_hop: bool,
    /// Which destinations MPLS engineers traffic for: `bgp`, `bgp-igp`, `bgp-igp-both-ribs` or `mpls-forwarding`.
    pub traffic_engineering: Option<String>,
    /// Seconds.
    pub optimize_timer: Option<String>,
    /// Seconds.
    pub optimize_switchover_delay: Option<String>,
    /// Seconds.
    pub optimize_hold_dead_delay: Option<String>,
    /// Seconds.
    pub smart_optimize_timer: Option<String>,
    /// Seconds.
    pub rsvp_error_hold_time: Option<String>,
    pub path_mtu: Option<MplsPathMtu>,
    pub log_updown: Option<MplsLogUpdown>,
    pub label_switched_paths: Vec<MplsLabelSwitchedPath>,
    /// The explicit hop lists that LSP paths refer to by name.
    pub paths: Vec<MplsPath>,
    pub static_label_switched_paths: Vec<MplsStaticLsp>,
    pub container_label_switched_paths: Vec<MplsContainerLsp>,
    pub traceoptions: Option<Traceoptions>,
    pub statistics: Option<MplsStatistics>,
    pub diffserv_te: Option<MplsDiffservTe>,
    /// The default `class-of-service` value of the LSPs.
    pub class_of_service: Option<String>,
    /// The default `<setup> <reservation>` priority of the LSPs, as written.
    pub priority: Option<String>,
    pub hop_limit: Option<String>,
    pub preference: Option<String>,
    /// Seconds.
    pub revert_timer: Option<String>,
    pub ultimate_hop_popping: bool,
    pub sensor_based_stats: bool,
}

/// Returns the `protocols mpls` block, or `None` if MPLS is not configured.
///
/// # Examples
///
/// ```
/// use asterust::config::juniper;
/// use asterust_junos::protocols::mpls::mpls;
///
/// let config = juniper::parse_braces("protocols {\n    mpls {\n        explicit-null;\n        interface ge-0/0/5.0;\n    }\n}\n");
/// let mpls = mpls(&config).unwrap();
/// assert!(mpls.explicit_null);
/// assert_eq!(mpls.interfaces[0].name, "ge-0/0/5.0");
/// ```
pub fn mpls(config: &Config) -> Option<Mpls> {
    let mpls = child_block(top_level(config, "protocols")?, "mpls")?;
    let field = |keyword: &str| arg_of(mpls, keyword).map(str::to_string);
    Some(Mpls {
        disable: has_leaf(mpls, "disable"),
        interfaces: named_children(mpls, "interface")
            .map(|(name, interface)| parse_interface(name, interface))
            .collect(),
        admin_groups: parse_admin_groups(mpls),
        explicit_null: has_leaf(mpls, "explicit-null"),
        no_cspf: has_leaf(mpls, "no-cspf"),
        no_propagate_ttl: has_leaf(mpls, "no-propagate-ttl"),
        no_decrement_ttl: has_leaf(mpls, "no-decrement-ttl"),
        ipv6_tunneling: has_leaf(mpls, "ipv6-tunneling"),
        expand_loose_hop: has_leaf(mpls, "expand-loose-hop"),
        traffic_engineering: field("traffic-engineering"),
        optimize_timer: field("optimize-timer"),
        optimize_switchover_delay: field("optimize-switchover-delay"),
        optimize_hold_dead_delay: field("optimize-hold-dead-delay"),
        smart_optimize_timer: field("smart-optimize-timer"),
        rsvp_error_hold_time: field("rsvp-error-hold-time"),
        path_mtu: parse_path_mtu(mpls),
        log_updown: parse_log_updown(mpls),
        label_switched_paths: named_children(mpls, "label-switched-path")
            .map(|(name, lsp)| parse_label_switched_path(name, lsp))
            .collect(),
        paths: named_children(mpls, "path")
            .map(|(name, path)| parse_path(name, path))
            .collect(),
        static_label_switched_paths: named_children(mpls, "static-label-switched-path")
            .map(|(name, lsp)| parse_static_lsp(name, lsp))
            .collect(),
        container_label_switched_paths: named_children(mpls, "container-label-switched-path")
            .map(|(name, lsp)| parse_container_lsp(name, lsp))
            .collect(),
        traceoptions: parse_traceoptions(mpls),
        statistics: parse_statistics(mpls),
        diffserv_te: parse_diffserv_te(mpls),
        class_of_service: field("class-of-service"),
        priority: field("priority"),
        hop_limit: field("hop-limit"),
        preference: field("preference"),
        revert_timer: field("revert-timer"),
        ultimate_hop_popping: has_leaf(mpls, "ultimate-hop-popping"),
        sensor_based_stats: has_leaf(mpls, "sensor-based-stats"),
    })
}

fn parse_admin_groups(mpls: &ConfigLine) -> Vec<MplsAdminGroup> {
    let Some(block) = child_block(mpls, "admin-groups") else {
        return Vec::new();
    };
    crate::active_children(block)
        .map(|group| {
            let (name, value) = split_name(&group.text);
            MplsAdminGroup {
                name: name.to_string(),
                value: value.to_string(),
            }
        })
        .collect()
}

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

    // Provider switch `show configuration` (MPLS part) of "Example: Configuring MPLS on EX8200 and EX4500 Switches"
    // (MPLS Applications User Guide, Basic MPLS Configuration), with the local PE's label-switched-path added from its
    // own results; see the README "Sources".
    const DOC_BASIC: &str = r#"
protocols {
    rsvp {
        interface lo0.0;
        interface ge-0/0/5.0;
    }
    mpls {
        label-switched-path lsp_to_pe2_ge1 {
            to 127.1.1.3;
        }
        interface ge-0/0/5.0;
        interface ge-0/0/6.0;
        interface ae0.0;
    }
    ospf {
        traffic-engineering;
    }
}
"#;

    // Not from documentation: written from the CLI Reference pages of the statements. See the README "Sources".
    const EXTRA: &str = r#"
protocols {
    mpls {
        explicit-null;
        no-cspf;
        no-propagate-ttl;
        no-decrement-ttl;
        ipv6-tunneling;
        expand-loose-hop;
        traffic-engineering bgp-igp;
        optimize-timer 3600;
        optimize-switchover-delay 5;
        optimize-hold-dead-delay 10;
        smart-optimize-timer 180;
        rsvp-error-hold-time 25;
        admin-groups {
            gold 1;
            silver 2;
        }
        path-mtu {
            allow-fragmentation;
            rsvp {
                mtu-signaling;
            }
        }
        log-updown {
            no-trap {
                mpls-lsp-traps;
            }
            no-syslog;
            trap;
            trap-path-down;
        }
        interface all {
            admin-group [ gold silver ];
            srlg SRLG-A;
        }
        interface fxp0.0 {
            disable;
        }
    }
}
"#;

    #[test]
    fn reads_the_guide_interfaces() {
        let mpls = mpls(&juniper::parse_braces(DOC_BASIC)).unwrap();
        assert!(!mpls.disable);
        let names: Vec<&str> = mpls.interfaces.iter().map(|i| i.name.as_str()).collect();
        assert_eq!(names, ["ge-0/0/5.0", "ge-0/0/6.0", "ae0.0"]);
        assert!(mpls.interfaces.iter().all(|i| !i.disable));
        assert!(!mpls.explicit_null);
        assert_eq!(mpls.path_mtu, None);
    }

    #[test]
    fn reads_the_guide_label_switched_path() {
        let mpls = mpls(&juniper::parse_braces(DOC_BASIC)).unwrap();
        assert_eq!(mpls.label_switched_paths.len(), 1);
        let lsp = &mpls.label_switched_paths[0];
        assert_eq!(lsp.name, "lsp_to_pe2_ge1");
        assert_eq!(lsp.to.as_deref(), Some("127.1.1.3"));
        assert_eq!(lsp.from, None);
        assert!(lsp.primary.is_empty());
        assert_eq!(lsp.fast_reroute, None);
    }

    // Not from documentation: written from the CLI Reference pages of `label-switched-path`, `primary`, `secondary` and
    // `fast-reroute`. See the README "Sources".
    const LSPS: &str = r#"
protocols {
    mpls {
        label-switched-path to-R3 {
            description "to R3";
            to 10.255.0.3;
            from 10.255.0.1;
            adaptive;
            bandwidth 100m;
            class-of-service 3;
            metric 50;
            preference 5;
            priority 3 3;
            no-record;
            random;
            retry-limit 10;
            retry-timer 30;
            revert-timer 120;
            optimize-timer 600;
            link-protection;
            soft-preemption;
            ldp-tunneling;
            install 10.9.0.0/24 active;
            install 10.9.1.0/24;
            admin-group {
                include-any [ gold silver ];
                exclude red;
            }
            fast-reroute {
                bandwidth 10m;
                hop-limit 5;
                include-all [ gold ];
            }
            primary via-A {
                bandwidth 50m;
                hop-limit 8;
                priority 4 4;
                record;
                select manual;
                standby;
            }
            secondary via-B;
            secondary via-C standby;
        }
        label-switched-path DOWN {
            to 10.255.0.4;
            admin-down;
            disable;
            no-cspf;
            node-link-protection;
            fast-reroute;
            most-fill;
            no-self-ping;
        }
    }
}
"#;

    #[test]
    fn reads_the_label_switched_path_options() {
        let mpls = mpls(&juniper::parse_braces(LSPS)).unwrap();
        assert_eq!(mpls.label_switched_paths.len(), 2);
        let lsp = &mpls.label_switched_paths[0];
        assert_eq!(lsp.description.as_deref(), Some("to R3"));
        assert_eq!(lsp.to.as_deref(), Some("10.255.0.3"));
        assert_eq!(lsp.from.as_deref(), Some("10.255.0.1"));
        assert!(lsp.adaptive);
        assert_eq!(lsp.bandwidth.as_deref(), Some("100m"));
        assert_eq!(lsp.class_of_service.as_deref(), Some("3"));
        assert_eq!(lsp.metric.as_deref(), Some("50"));
        assert_eq!(lsp.preference.as_deref(), Some("5"));
        assert_eq!(lsp.priority.as_deref(), Some("3 3"));
        assert_eq!(lsp.record, Some(false));
        assert_eq!(lsp.path_selection.as_deref(), Some("random"));
        assert_eq!(lsp.retry_limit.as_deref(), Some("10"));
        assert_eq!(lsp.retry_timer.as_deref(), Some("30"));
        assert_eq!(lsp.revert_timer.as_deref(), Some("120"));
        assert_eq!(lsp.optimize_timer.as_deref(), Some("600"));
        assert!(lsp.link_protection);
        assert!(lsp.soft_preemption);
        assert!(lsp.ldp_tunneling);
        assert_eq!(lsp.install, ["10.9.0.0/24", "10.9.1.0/24"]);
        assert_eq!(lsp.admin_group.include_any, ["gold", "silver"]);
        assert_eq!(lsp.admin_group.exclude, ["red"]);
        assert!(lsp.admin_group.include_all.is_empty());
    }

    #[test]
    fn reads_fast_reroute_and_flags() {
        let mpls = mpls(&juniper::parse_braces(LSPS)).unwrap();
        let reroute = mpls.label_switched_paths[0].fast_reroute.as_ref().unwrap();
        assert_eq!(reroute.bandwidth.as_deref(), Some("10m"));
        assert_eq!(reroute.hop_limit.as_deref(), Some("5"));
        assert_eq!(reroute.include_all, ["gold"]);
        assert_eq!(reroute.bandwidth_percent, None);

        let down = &mpls.label_switched_paths[1];
        assert!(down.admin_down);
        assert!(down.disable);
        assert!(down.no_cspf);
        assert!(down.node_link_protection);
        assert!(down.no_self_ping);
        assert_eq!(down.path_selection.as_deref(), Some("most-fill"));
        assert_eq!(down.fast_reroute, Some(MplsFastReroute::default()));
        assert_eq!(down.record, None);
    }

    #[test]
    fn reads_primary_and_secondary_paths() {
        let mpls = mpls(&juniper::parse_braces(LSPS)).unwrap();
        let lsp = &mpls.label_switched_paths[0];
        assert_eq!(lsp.primary.len(), 1);
        let primary = &lsp.primary[0];
        assert_eq!(primary.name, "via-A");
        assert_eq!(primary.bandwidth.as_deref(), Some("50m"));
        assert_eq!(primary.hop_limit.as_deref(), Some("8"));
        assert_eq!(primary.priority.as_deref(), Some("4 4"));
        assert_eq!(primary.record, Some(true));
        assert_eq!(primary.select.as_deref(), Some("manual"));
        assert!(primary.standby);

        assert_eq!(lsp.secondary.len(), 2);
        assert_eq!(lsp.secondary[0].name, "via-B");
        assert!(!lsp.secondary[0].standby);
        assert_eq!(lsp.secondary[1].name, "via-C");
        assert!(lsp.secondary[1].standby);
    }

    // Not from documentation: written from the CLI Reference pages of `path`, `static-label-switched-path` and
    // `container-label-switched-path`. See the README "Sources".
    const STATIC_AND_PATHS: &str = r#"
protocols {
    mpls {
        path via-A {
            10.0.0.2 strict;
            10.0.0.3 loose;
            core-hop abstract;
            r5.example.net;
        }
        path unconstrained;
        static-label-switched-path ingress-lsp {
            ingress {
                to 10.255.0.9;
                push 1000001;
                next-hop 10.1.1.2;
                bandwidth 10m;
                class-of-service 2;
                description "static ingress";
                metric 5;
                preference 4;
                no-install-to-address;
                install 10.7.0.0/24 active;
                link-protection bypass-name byp1;
                node-protection bypass-name byp2 next-next-label 3000;
            }
        }
        static-label-switched-path transit-lsp {
            transit 1000001 {
                swap 1000002;
                next-hop ge-0/0/1.0;
                bandwidth 5m;
                link-protection bypass-name byp1;
            }
            transit 1000009 {
                pop;
                next-hop 10.1.2.2/ge-0/0/2.0;
            }
            bypass byp1 {
                to 10.255.0.4;
                next-hop 10.1.3.2;
                next-table inet.0 push 2000;
                description "backup";
            }
        }
        container-label-switched-path CONT {
            to 10.255.0.7;
            description "multi-LSP";
            suffix -member;
            label-switched-path-template TEMPLATE-A;
            splitting-merging {
                maximum-member-lsps 4;
            }
        }
        container-label-switched-path CONT-OFF {
            disable;
        }
    }
}
"#;

    #[test]
    fn reads_paths() {
        let mpls = mpls(&juniper::parse_braces(STATIC_AND_PATHS)).unwrap();
        assert_eq!(mpls.paths.len(), 2);
        let path = &mpls.paths[0];
        assert_eq!(path.name, "via-A");
        let hops: Vec<(&str, Option<&str>)> = path
            .hops
            .iter()
            .map(|h| (h.address.as_str(), h.qualifier.as_deref()))
            .collect();
        assert_eq!(
            hops,
            [
                ("10.0.0.2", Some("strict")),
                ("10.0.0.3", Some("loose")),
                ("core-hop", Some("abstract")),
                ("r5.example.net", None),
            ]
        );
        assert_eq!(mpls.paths[1].name, "unconstrained");
        assert!(mpls.paths[1].hops.is_empty());
    }

    #[test]
    fn reads_static_ingress() {
        let mpls = mpls(&juniper::parse_braces(STATIC_AND_PATHS)).unwrap();
        assert_eq!(mpls.static_label_switched_paths.len(), 2);
        let lsp = &mpls.static_label_switched_paths[0];
        assert_eq!(lsp.name, "ingress-lsp");
        assert!(lsp.transit.is_empty());
        let ingress = lsp.ingress.as_ref().unwrap();
        assert_eq!(ingress.to.as_deref(), Some("10.255.0.9"));
        assert_eq!(ingress.push.as_deref(), Some("1000001"));
        assert_eq!(ingress.next_hop.as_deref(), Some("10.1.1.2"));
        assert_eq!(ingress.bandwidth.as_deref(), Some("10m"));
        assert_eq!(ingress.class_of_service.as_deref(), Some("2"));
        assert_eq!(ingress.description.as_deref(), Some("static ingress"));
        assert_eq!(ingress.metric.as_deref(), Some("5"));
        assert_eq!(ingress.preference.as_deref(), Some("4"));
        assert!(ingress.no_install_to_address);
        assert_eq!(ingress.install, ["10.7.0.0/24"]);
        assert_eq!(ingress.link_protection.as_deref(), Some("byp1"));
        let node = ingress.node_protection.as_ref().unwrap();
        assert_eq!(node.bypass_name.as_deref(), Some("byp2"));
        assert_eq!(node.next_next_label.as_deref(), Some("3000"));
    }

    #[test]
    fn reads_static_transit_and_bypass() {
        let mpls = mpls(&juniper::parse_braces(STATIC_AND_PATHS)).unwrap();
        let lsp = &mpls.static_label_switched_paths[1];
        assert_eq!(lsp.ingress, None);
        assert_eq!(lsp.transit.len(), 2);
        assert_eq!(lsp.transit[0].incoming_label, "1000001");
        assert_eq!(lsp.transit[0].swap.as_deref(), Some("1000002"));
        assert_eq!(lsp.transit[0].next_hop.as_deref(), Some("ge-0/0/1.0"));
        assert_eq!(lsp.transit[0].bandwidth.as_deref(), Some("5m"));
        assert_eq!(lsp.transit[0].link_protection.as_deref(), Some("byp1"));
        assert!(!lsp.transit[0].pop);
        assert!(lsp.transit[1].pop);
        assert_eq!(lsp.transit[1].next_hop.as_deref(), Some("10.1.2.2/ge-0/0/2.0"));

        assert_eq!(lsp.bypasses.len(), 1);
        let bypass = &lsp.bypasses[0];
        assert_eq!(bypass.name, "byp1");
        assert_eq!(bypass.to.as_deref(), Some("10.255.0.4"));
        assert_eq!(bypass.next_hop.as_deref(), Some("10.1.3.2"));
        assert_eq!(bypass.next_table.as_deref(), Some("inet.0 push 2000"));
        assert_eq!(bypass.description.as_deref(), Some("backup"));
    }

    #[test]
    fn reads_container_lsps() {
        let mpls = mpls(&juniper::parse_braces(STATIC_AND_PATHS)).unwrap();
        assert_eq!(mpls.container_label_switched_paths.len(), 2);
        let container = &mpls.container_label_switched_paths[0];
        assert_eq!(container.name, "CONT");
        assert_eq!(container.to.as_deref(), Some("10.255.0.7"));
        assert_eq!(container.description.as_deref(), Some("multi-LSP"));
        assert_eq!(container.suffix.as_deref(), Some("-member"));
        assert_eq!(container.label_switched_path_template.as_deref(), Some("TEMPLATE-A"));
        assert!(container.splitting_merging);
        assert!(!container.disable);

        let off = &mpls.container_label_switched_paths[1];
        assert!(off.disable);
        assert!(!off.splitting_merging);
    }

    #[test]
    fn reads_the_flags_and_timers() {
        let mpls = mpls(&juniper::parse_braces(EXTRA)).unwrap();
        assert!(mpls.explicit_null);
        assert!(mpls.no_cspf);
        assert!(mpls.no_propagate_ttl);
        assert!(mpls.no_decrement_ttl);
        assert!(mpls.ipv6_tunneling);
        assert!(mpls.expand_loose_hop);
        assert_eq!(mpls.traffic_engineering.as_deref(), Some("bgp-igp"));
        assert_eq!(mpls.optimize_timer.as_deref(), Some("3600"));
        assert_eq!(mpls.optimize_switchover_delay.as_deref(), Some("5"));
        assert_eq!(mpls.optimize_hold_dead_delay.as_deref(), Some("10"));
        assert_eq!(mpls.smart_optimize_timer.as_deref(), Some("180"));
        assert_eq!(mpls.rsvp_error_hold_time.as_deref(), Some("25"));
    }

    #[test]
    fn reads_admin_groups_and_interface_options() {
        let mpls = mpls(&juniper::parse_braces(EXTRA)).unwrap();
        assert_eq!(mpls.admin_groups.len(), 2);
        assert_eq!(mpls.admin_groups[0].name, "gold");
        assert_eq!(mpls.admin_groups[0].value, "1");

        let all = &mpls.interfaces[0];
        assert_eq!(all.name, "all");
        assert_eq!(all.admin_groups, ["gold", "silver"]);
        assert_eq!(all.srlg, ["SRLG-A"]);
        assert!(mpls.interfaces[1].disable);
    }

    #[test]
    fn reads_path_mtu_and_log_updown() {
        let mpls = mpls(&juniper::parse_braces(EXTRA)).unwrap();
        let mtu = mpls.path_mtu.unwrap();
        assert!(mtu.allow_fragmentation);
        assert!(mtu.rsvp_mtu_signaling);

        let log = mpls.log_updown.unwrap();
        assert_eq!(log.syslog, Some(false));
        assert!(log.trap);
        assert!(log.trap_path_down);
        assert!(!log.trap_path_up);
        assert!(log.no_trap_mpls_lsp_traps);
        assert!(!log.no_trap_rfc3812_traps);
    }

    #[test]
    fn reads_a_bare_mpls_block() {
        let config = juniper::parse_braces("protocols {\n    mpls;\n}\n");
        assert_eq!(mpls(&config), Some(Mpls::default()));
    }

    #[test]
    fn no_mpls_is_none() {
        let config = juniper::parse_braces("protocols {\n    ospf {\n        area 0.0.0.0;\n    }\n}\n");
        assert_eq!(mpls(&config), None);
    }

    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
    const ROUTER_WIDE: &str = r#"
protocols {
    mpls {
        class-of-service 3;
        priority 4 4;
        hop-limit 10;
        preference 8;
        revert-timer 120;
        ultimate-hop-popping;
        sensor-based-stats;
        traceoptions {
            file mpls.log size 1m;
            flag state;
            flag all detail;
        }
    }
}
"#;

    #[test]
    fn reads_the_router_wide_lsp_defaults() {
        let mpls = mpls(&juniper::parse_braces(ROUTER_WIDE)).unwrap();
        assert_eq!(mpls.class_of_service.as_deref(), Some("3"));
        assert_eq!(mpls.priority.as_deref(), Some("4 4"));
        assert_eq!(mpls.hop_limit.as_deref(), Some("10"));
        assert_eq!(mpls.preference.as_deref(), Some("8"));
        assert_eq!(mpls.revert_timer.as_deref(), Some("120"));
        assert!(mpls.ultimate_hop_popping);
        assert!(mpls.sensor_based_stats);
    }

    #[test]
    fn reads_the_traceoptions() {
        let trace = mpls(&juniper::parse_braces(ROUTER_WIDE)).unwrap().traceoptions.unwrap();
        assert_eq!(trace.file.as_deref(), Some("mpls.log"));
        assert_eq!(trace.size.as_deref(), Some("1m"));
        assert_eq!(trace.flags[0].name, "state");
        assert_eq!(trace.flags[1].name, "all");
        assert_eq!(trace.flags[1].modifiers, ["detail"]);
    }

    #[test]
    fn router_wide_defaults_are_absent_by_default() {
        let mpls = mpls(&juniper::parse_braces(
            "protocols {\n    mpls {\n        no-cspf;\n    }\n}\n",
        ))
        .unwrap();
        assert_eq!(mpls.class_of_service, None);
        assert_eq!(mpls.priority, None);
        assert_eq!(mpls.traceoptions, None);
        assert_eq!(mpls.statistics, None);
        assert_eq!(mpls.diffserv_te, None);
        assert!(!mpls.ultimate_hop_popping);
    }

    // The MPLS `traceoptions` of the automatic bandwidth tracing sample of Basic LSP Configuration (MPLS Applications
    // User Guide); see the README "Sources".
    const DOC_TRACEOPTIONS: &str = r#"
protocols {
    mpls {
        traceoptions {
            file auto-band-trace size 10k files 10 world-readable;
            flag autobw-state;
        }
    }
}
"#;

    #[test]
    fn reads_the_guide_traceoptions() {
        let trace = mpls(&juniper::parse_braces(DOC_TRACEOPTIONS))
            .unwrap()
            .traceoptions
            .unwrap();
        assert_eq!(trace.file.as_deref(), Some("auto-band-trace"));
        assert_eq!(trace.size.as_deref(), Some("10k"));
        assert_eq!(trace.files.as_deref(), Some("10"));
        assert_eq!(trace.world_readable, Some(true));
        assert_eq!(trace.flags[0].name, "autobw-state");
    }
}