1use crate::{
14 active_children, arg_of, child_block, has_leaf, list_values, split_keyword, split_name, statements, unquote,
15};
16use asterust::config::ConfigLine;
17
18#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct RouteFilter {
22 pub prefix: String,
23 pub match_type: Option<String>,
25}
26
27#[derive(Clone, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct ValidationDatabaseMatch {
31 pub name: String,
32 pub state: Option<String>,
34}
35
36#[derive(Clone, Debug, Default, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct ValidationDatabaseInstance {
40 pub state: Option<String>,
42 pub databases: Vec<ValidationDatabaseMatch>,
43}
44
45#[derive(Clone, Debug, Default, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct PolicyConditions {
50 pub protocols: Vec<String>,
51 pub families: Vec<String>,
52 pub communities: Vec<String>,
53 pub as_paths: Vec<String>,
54 pub prefix_lists: Vec<String>,
55 pub prefix_list_filters: Vec<String>,
57 pub route_filters: Vec<RouteFilter>,
58 pub neighbors: Vec<String>,
59 pub policies: Vec<String>,
61 pub aggregate_contributor: bool,
63 pub areas: Vec<String>,
65 pub as_path_groups: Vec<String>,
67 pub as_path_neighbors: Vec<String>,
70 pub as_path_origins: Vec<String>,
71 pub as_path_transits: Vec<String>,
72 pub as_path_unique_count: Option<String>,
74 pub as_path_calc_length: Option<String>,
76 pub color: Option<String>,
78 pub community_count: Option<String>,
80 pub conditions: Vec<String>,
82 pub external: bool,
84 pub external_type: Option<String>,
86 pub internal: bool,
88 pub interfaces: Vec<String>,
89 pub level: Option<String>,
91 pub local_preference: Option<String>,
92 pub metric: Option<String>,
94 pub mac_filter_lists: Vec<String>,
95 pub multicast_scoping: Option<String>,
97 pub next_hops: Vec<String>,
98 pub next_hop_type: Option<String>,
100 pub nlri_route_types: Vec<String>,
102 pub origin: Option<String>,
103 pub preference: Option<String>,
105 pub programmed: bool,
107 pub ribs: Vec<String>,
109 pub route_filter_lists: Vec<String>,
110 pub route_type: Option<String>,
112 pub rtf_prefix_lists: Vec<String>,
114 pub source_address_filter_lists: Vec<String>,
115 pub source_address_filters: Vec<RouteFilter>,
117 pub state: Option<String>,
119 pub tag: Option<String>,
121 pub traffic_engineering: bool,
123 pub validation_database: Option<String>,
125 pub validation_database_instance: Option<ValidationDatabaseInstance>,
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131#[non_exhaustive]
132pub enum PolicyAction {
133 Accept,
134 Reject,
135 NextTerm,
136 NextPolicy,
137}
138
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum CommunityOperation {
143 Add,
144 Set,
145 Delete,
146}
147
148#[derive(Clone, Debug, PartialEq, Eq)]
150#[non_exhaustive]
151pub struct CommunityAction {
152 pub operation: CommunityOperation,
153 pub community: String,
154}
155
156#[derive(Clone, Debug, PartialEq, Eq)]
158#[non_exhaustive]
159pub struct PolicySrv6Action {
160 pub locator: String,
161 pub sid_type: Option<String>,
163 pub sid_value: Option<String>,
165}
166
167#[derive(Clone, Debug, Default, PartialEq, Eq)]
169#[non_exhaustive]
170pub struct PolicyPrefixSegment {
171 pub index: Option<String>,
172 pub node_segment: bool,
173}
174
175#[derive(Clone, Debug, Default, PartialEq, Eq)]
177#[non_exhaustive]
178pub struct PolicyActions {
179 pub action: Option<PolicyAction>,
180 pub metric: Option<String>,
182 pub local_preference: Option<String>,
183 pub next_hop: Option<String>,
184 pub as_path_prepend: Option<String>,
185 pub communities: Vec<CommunityAction>,
186 pub load_balance: Option<String>,
188 pub resolution_map: Option<String>,
190 pub multipath_resolve: bool,
191 pub srv6: Option<PolicySrv6Action>,
192 pub default_action: Option<PolicyAction>,
194 pub add_path: Option<String>,
196 pub advertise_locator: bool,
197 pub aggregate_bandwidth: bool,
198 pub aggregate_weight: Option<String>,
200 pub aigp_originate: bool,
202 pub aigp_distance: Option<String>,
203 pub as_path_expand: Option<String>,
205 pub assisted_replication: Option<String>,
207 pub bgp_output_queue_priority: Option<String>,
208 pub class: Option<String>,
210 pub color: Option<String>,
212 pub cos_next_hop_map: Option<String>,
213 pub damping: Option<String>,
215 pub destination_class: Option<String>,
216 pub dynamic_tunnel_attributes: Option<String>,
217 pub external: Option<String>,
219 pub forwarding_class: Option<String>,
220 pub install_nexthop: Option<String>,
222 pub install_to_fib: Option<bool>,
224 pub limit_bandwidth: Option<String>,
225 pub map_to_interface: Option<String>,
226 pub no_entropy_label_capability: bool,
227 pub origin: Option<String>,
228 pub preference: Option<String>,
230 pub prefix_attribute_flags: bool,
231 pub prefix_segment: Option<PolicyPrefixSegment>,
232 pub priority: Option<String>,
234 pub set_down_bit: bool,
235 pub source_class: Option<String>,
236 pub sr_te_template: Option<String>,
237 pub ssm_sources: Vec<String>,
238 pub tag: Option<String>,
240 pub validation_state: Option<String>,
242}
243
244#[derive(Clone, Debug, PartialEq, Eq)]
246#[non_exhaustive]
247pub struct PolicyTerm {
248 pub name: Option<String>,
251 pub from: PolicyConditions,
252 pub to: PolicyConditions,
253 pub then: PolicyActions,
254}
255
256pub(super) fn parse_term(name: Option<&str>, line: &ConfigLine) -> PolicyTerm {
257 PolicyTerm {
258 name: name.map(str::to_string),
259 from: parse_conditions(line, "from"),
260 to: parse_conditions(line, "to"),
261 then: parse_actions(line),
262 }
263}
264
265fn parse_conditions(line: &ConfigLine, keyword: &str) -> PolicyConditions {
266 let mut conditions = PolicyConditions {
267 validation_database_instance: active_children(line)
268 .filter(|c| c.text == keyword)
269 .find_map(|block| child_block(block, "validation-database-instance"))
270 .map(parse_validation_database_instance),
271 ..PolicyConditions::default()
272 };
273 for statement in statements(line, keyword) {
274 let (condition, arg) = split_keyword(statement);
275 match condition {
276 "protocol" => conditions.protocols.extend(list_values(arg)),
277 "family" => conditions.families.push(unquote(arg).to_string()),
278 "community" => conditions.communities.extend(list_values(arg)),
279 "as-path" => conditions.as_paths.extend(list_values(arg)),
280 "prefix-list" => conditions.prefix_lists.extend(list_values(arg)),
281 "prefix-list-filter" => conditions.prefix_list_filters.push(arg.to_string()),
282 "route-filter" => conditions.route_filters.push(parse_route_filter(arg)),
283 "neighbor" => conditions.neighbors.push(unquote(arg).to_string()),
284 "policy" => conditions.policies.push(unquote(arg).to_string()),
285 "aggregate-contributor" => conditions.aggregate_contributor = true,
286 "area" => conditions.areas.push(arg.to_string()),
287 "as-path-group" => conditions.as_path_groups.extend(list_values(arg)),
288 "as-path-neighbors" => conditions.as_path_neighbors.push(arg.to_string()),
289 "as-path-origins" => conditions.as_path_origins.push(arg.to_string()),
290 "as-path-transits" => conditions.as_path_transits.push(arg.to_string()),
291 "as-path-unique-count" => conditions.as_path_unique_count = rest(arg),
292 "as-path-calc-length" => conditions.as_path_calc_length = rest(arg),
293 "color" => conditions.color = rest(arg),
294 "community-count" => conditions.community_count = rest(arg),
295 "condition" => conditions.conditions.extend(list_values(arg)),
296 "external" => {
297 conditions.external = true;
298 conditions.external_type = arg.strip_prefix("type").and_then(|t| rest(t.trim()));
299 }
300 "internal" => conditions.internal = true,
301 "interface" => conditions.interfaces.extend(list_values(arg)),
302 "level" => conditions.level = rest(arg),
303 "local-preference" => conditions.local_preference = rest(arg),
304 "metric" => conditions.metric = rest(arg),
305 "mac-filter-list" => conditions.mac_filter_lists.extend(list_values(arg)),
306 "multicast-scoping" => conditions.multicast_scoping = rest(arg),
307 "next-hop" => conditions.next_hops.extend(list_values(arg)),
308 "next-hop-type" => conditions.next_hop_type = rest(arg),
309 "nlri-route-type" => conditions.nlri_route_types.extend(list_values(arg)),
310 "origin" => conditions.origin = rest(arg),
311 "preference" => conditions.preference = rest(arg),
312 "programmed" => conditions.programmed = true,
313 "rib" => conditions.ribs.extend(list_values(arg)),
314 "route-filter-list" => conditions.route_filter_lists.extend(list_values(arg)),
315 "route-type" => conditions.route_type = rest(arg),
316 "rtf-prefix-list" => conditions.rtf_prefix_lists.push(arg.to_string()),
317 "source-address-filter-list" => conditions.source_address_filter_lists.extend(list_values(arg)),
318 "source-address-filter" => conditions.source_address_filters.push(parse_route_filter(arg)),
319 "state" => conditions.state = rest(arg),
320 "tag" => conditions.tag = rest(arg),
321 "traffic-engineering" => conditions.traffic_engineering = true,
322 "validation-database" => conditions.validation_database = rest(arg),
323 _ => {}
324 }
325 }
326 conditions
327}
328
329fn parse_validation_database_instance(line: &ConfigLine) -> ValidationDatabaseInstance {
330 ValidationDatabaseInstance {
331 state: arg_of(line, "state").map(str::to_string),
332 databases: active_children(line)
333 .filter_map(|c| c.arg("database"))
334 .map(|arg| {
335 let (name, after) = split_name(arg);
336 ValidationDatabaseMatch {
337 name: unquote(name).to_string(),
338 state: after.strip_prefix("state").and_then(|s| rest(s.trim())),
339 }
340 })
341 .collect(),
342 }
343}
344
345fn rest(arg: &str) -> Option<String> {
346 Some(arg).filter(|a| !a.is_empty()).map(str::to_string)
347}
348
349fn parse_route_filter(arg: &str) -> RouteFilter {
350 let (prefix, match_type) = split_keyword(arg);
351 RouteFilter {
352 prefix: prefix.to_string(),
353 match_type: Some(match_type).filter(|m| !m.is_empty()).map(str::to_string),
354 }
355}
356
357fn parse_actions(line: &ConfigLine) -> PolicyActions {
358 let mut actions = PolicyActions::default();
359 for statement in statements(line, "then") {
360 let (action, arg) = split_keyword(statement);
361 let value = || Some(unquote(arg).to_string());
362 match (action, arg) {
363 ("accept", "") => actions.action = Some(PolicyAction::Accept),
364 ("reject", "") => actions.action = Some(PolicyAction::Reject),
365 ("next", "term") => actions.action = Some(PolicyAction::NextTerm),
366 ("next", "policy") => actions.action = Some(PolicyAction::NextPolicy),
367 ("metric", _) => actions.metric = value(),
368 ("local-preference", _) => actions.local_preference = value(),
369 ("next-hop", _) => actions.next_hop = value(),
370 ("as-path-prepend", _) => actions.as_path_prepend = value(),
371 ("community", _) => actions.communities.extend(parse_community_actions(arg)),
372 ("load-balance", _) => actions.load_balance = Some(arg.to_string()).filter(|a| !a.is_empty()),
373 ("resolution-map", _) => actions.resolution_map = value(),
374 ("multipath-resolve", "") => actions.multipath_resolve = true,
375 ("srv6", _) => actions.srv6 = parse_srv6_action(arg),
376 ("default-action", "accept") => actions.default_action = Some(PolicyAction::Accept),
377 ("default-action", "reject") => actions.default_action = Some(PolicyAction::Reject),
378 ("add-path", _) => actions.add_path = value(),
379 ("advertise-locator", "") => actions.advertise_locator = true,
380 ("aggregate-bandwidth", "") => actions.aggregate_bandwidth = true,
381 ("aigp-originate", _) => {
382 actions.aigp_originate = true;
383 actions.aigp_distance = arg.strip_prefix("distance").map(|d| d.trim().to_string());
384 }
385 ("as-path-expand", _) => actions.as_path_expand = value(),
386 ("assisted-replication", _) => actions.assisted_replication = value(),
387 ("bgp-output-queue-priority", _) => actions.bgp_output_queue_priority = value(),
388 ("class", _) => actions.class = value(),
389 ("color", _) => actions.color = value(),
390 ("cos-next-hop-map", _) => actions.cos_next_hop_map = value(),
391 ("damping", _) => actions.damping = value(),
392 ("destination-class", _) => actions.destination_class = value(),
393 ("dynamic-tunnel-attributes", _) => actions.dynamic_tunnel_attributes = value(),
394 ("external", _) => actions.external = value(),
395 ("forwarding-class", _) => actions.forwarding_class = value(),
396 ("install-nexthop", _) => actions.install_nexthop = value(),
397 ("install-to-fib", "") => actions.install_to_fib = Some(true),
398 ("no-install-to-fib", "") => actions.install_to_fib = Some(false),
399 ("limit-bandwidth", _) => actions.limit_bandwidth = value(),
400 ("map-to-interface", _) => actions.map_to_interface = value(),
401 ("no-entropy-label-capability", "") => actions.no_entropy_label_capability = true,
402 ("origin", _) => actions.origin = value(),
403 ("preference", _) => actions.preference = value(),
404 ("prefix-attribute-flags", "") => actions.prefix_attribute_flags = true,
405 ("priority", _) => actions.priority = value(),
406 ("set-down-bit", "") => actions.set_down_bit = true,
407 ("source-class", _) => actions.source_class = value(),
408 ("sr-te-template", _) => actions.sr_te_template = value(),
409 ("ssm-source", _) => actions.ssm_sources.extend(list_values(arg)),
410 ("tag", _) => actions.tag = value(),
411 ("validation-state", _) => actions.validation_state = value(),
412 _ => {}
413 }
414 }
415 for block in active_children(line).filter(|c| c.text == "then") {
416 if let Some(weight) = child_block(block, "aggregate-weight") {
417 actions.aggregate_weight = arg_of(weight, "multiplier").map(str::to_string);
418 }
419 if let Some(segment) = child_block(block, "prefix-segment") {
420 actions.prefix_segment = Some(PolicyPrefixSegment {
421 index: arg_of(segment, "index").map(str::to_string),
422 node_segment: has_leaf(segment, "node-segment"),
423 });
424 }
425 }
426 actions
427}
428
429fn parse_srv6_action(arg: &str) -> Option<PolicySrv6Action> {
430 let (locator, sid) = split_name(arg.strip_prefix("locator")?.trim());
431 let (sid_type, sid_value) = split_keyword(sid);
432 Some(PolicySrv6Action {
433 locator: unquote(locator).to_string(),
434 sid_type: Some(sid_type).filter(|t| !t.is_empty()).map(str::to_string),
435 sid_value: Some(sid_value).filter(|v| !v.is_empty()).map(str::to_string),
436 })
437}
438
439fn parse_community_actions(arg: &str) -> Vec<CommunityAction> {
440 let (operation, communities) = split_name(arg);
441 let operation = match operation {
442 "add" | "+" => CommunityOperation::Add,
443 "set" | "=" => CommunityOperation::Set,
444 "delete" | "-" => CommunityOperation::Delete,
445 _ => return Vec::new(),
446 };
447 list_values(communities)
448 .into_iter()
449 .map(|community| CommunityAction { operation, community })
450 .collect()
451}
452
453#[cfg(test)]
454mod tests {
455 use crate::policy_options::{
456 policy_options, CommunityOperation, PolicyAction, PolicyActions, PolicyConditions, PolicyOptions,
457 };
458 use asterust::config::juniper;
459
460 fn parse(text: &str) -> PolicyOptions {
461 policy_options(&juniper::parse_braces(text)).expect("fixture has a policy-options block")
462 }
463
464 fn from_of(options: &PolicyOptions, policy: usize, term: usize) -> &PolicyConditions {
465 &options.policy_statements[policy].terms[term].from
466 }
467
468 const DOC_CONDITIONS: &str = r#"
474policy-options {
475 policy-statement import-communities {
476 term 1 {
477 from {
478 protocol bgp;
479 community-count 5 orlower;
480 }
481 then accept;
482 }
483 term 2 {
484 then reject;
485 }
486 }
487 policy-statement join-filter {
488 from {
489 neighbor 10.14.12.20;
490 source-address-filter 10.83.0.0/16 orlonger;
491 }
492 then reject;
493 }
494 policy-statement join-filter-interface {
495 from {
496 interface so-1/0/0.0;
497 source-address-filter 10.83.0.0/16 orlonger;
498 }
499 then reject;
500 }
501 policy-statement as-list-match {
502 term neighbor-match {
503 from as-path-neighbors as-list peer-match;
504 }
505 term group-match {
506 from as-path-origins as-list-group origin_group;
507 }
508 }
509 policy-statement rf-test-policy {
510 term term2 {
511 from route-filter-list rf-list-1;
512 }
513 }
514 policy-statement conditional-export-bgp {
515 term conditional-default {
516 from {
517 condition prefix_11;
518 route-filter 0.0.0.0/0 exact;
519 }
520 then accept;
521 }
522 }
523 policy-statement dampPolicy {
524 term term1 {
525 from nlri-route-type [ 3 4 5 ];
526 }
527 }
528 policy-statement vrf-leak {
529 term 1 {
530 from {
531 protocol bgp;
532 rib vrf-customer2.inet.0;
533 community customer;
534 }
535 }
536 }
537}
538"#;
539
540 #[test]
541 fn reads_the_guide_community_count() {
542 let options = parse(DOC_CONDITIONS);
543 let from = from_of(&options, 0, 0);
544 assert_eq!(from.protocols, ["bgp"]);
545 assert_eq!(from.community_count.as_deref(), Some("5 orlower"));
546 assert_eq!(from_of(&options, 0, 1).community_count, None);
547 }
548
549 #[test]
550 fn reads_the_guide_source_address_filters() {
551 let options = parse(DOC_CONDITIONS);
552 let from = from_of(&options, 1, 0);
553 assert_eq!(from.neighbors, ["10.14.12.20"]);
554 assert_eq!(from.source_address_filters.len(), 1);
555 assert_eq!(from.source_address_filters[0].prefix, "10.83.0.0/16");
556 assert_eq!(from.source_address_filters[0].match_type.as_deref(), Some("orlonger"));
557
558 let from = from_of(&options, 2, 0);
559 assert_eq!(from.interfaces, ["so-1/0/0.0"]);
560 }
561
562 #[test]
563 fn reads_the_guide_as_lists() {
564 let options = parse(DOC_CONDITIONS);
565 assert_eq!(from_of(&options, 3, 0).as_path_neighbors, ["as-list peer-match"]);
566 assert_eq!(from_of(&options, 3, 1).as_path_origins, ["as-list-group origin_group"]);
567 }
568
569 #[test]
570 fn reads_the_guide_lists_and_conditions() {
571 let options = parse(DOC_CONDITIONS);
572 assert_eq!(from_of(&options, 4, 0).route_filter_lists, ["rf-list-1"]);
573
574 let from = from_of(&options, 5, 0);
575 assert_eq!(from.conditions, ["prefix_11"]);
576 assert_eq!(from.route_filters[0].prefix, "0.0.0.0/0");
577 }
578
579 #[test]
580 fn reads_the_guide_nlri_route_types_and_rib() {
581 let options = parse(DOC_CONDITIONS);
582 assert_eq!(from_of(&options, 6, 0).nlri_route_types, ["3", "4", "5"]);
583
584 let from = from_of(&options, 7, 0);
585 assert_eq!(from.ribs, ["vrf-customer2.inet.0"]);
586 assert_eq!(from.communities, ["customer"]);
587 }
588
589 #[test]
592 fn reads_the_other_match_conditions() {
593 let options = parse(
594 r#"
595policy-options {
596 policy-statement igp {
597 term ospf {
598 from {
599 protocol ospf;
600 area 0.0.0.0;
601 external type 2;
602 level 2;
603 tag 100 tag2 200;
604 state active;
605 aggregate-contributor;
606 programmed;
607 traffic-engineering;
608 }
609 }
610 term internal {
611 from {
612 internal;
613 route-type external;
614 color 10 color2 5;
615 metric 20 metric2 30;
616 preference 100 preference2 200;
617 local-preference 150;
618 origin igp;
619 next-hop [ 192.0.2.1 192.0.2.2 ];
620 next-hop-type merged;
621 as-path-group TRANSIT;
622 as-path-unique-count 2 orhigher;
623 as-path-calc-length 4 equal;
624 mac-filter-list MACS;
625 multicast-scoping link-local;
626 rtf-prefix-list RTF route-targets;
627 source-address-filter-list SOURCES;
628 }
629 }
630 term bare {
631 from external;
632 }
633 }
634}
635"#,
636 );
637 let ospf = from_of(&options, 0, 0);
638 assert_eq!(ospf.areas, ["0.0.0.0"]);
639 assert!(ospf.external);
640 assert_eq!(ospf.external_type.as_deref(), Some("2"));
641 assert_eq!(ospf.level.as_deref(), Some("2"));
642 assert_eq!(ospf.tag.as_deref(), Some("100 tag2 200"));
643 assert_eq!(ospf.state.as_deref(), Some("active"));
644 assert!(ospf.aggregate_contributor && ospf.programmed && ospf.traffic_engineering);
645 assert!(!ospf.internal);
646
647 let other = from_of(&options, 0, 1);
648 assert!(other.internal && !other.external);
649 assert_eq!(other.route_type.as_deref(), Some("external"));
650 assert_eq!(other.color.as_deref(), Some("10 color2 5"));
651 assert_eq!(other.metric.as_deref(), Some("20 metric2 30"));
652 assert_eq!(other.preference.as_deref(), Some("100 preference2 200"));
653 assert_eq!(other.local_preference.as_deref(), Some("150"));
654 assert_eq!(other.origin.as_deref(), Some("igp"));
655 assert_eq!(other.next_hops, ["192.0.2.1", "192.0.2.2"]);
656 assert_eq!(other.next_hop_type.as_deref(), Some("merged"));
657 assert_eq!(other.as_path_groups, ["TRANSIT"]);
658 assert_eq!(other.as_path_unique_count.as_deref(), Some("2 orhigher"));
659 assert_eq!(other.as_path_calc_length.as_deref(), Some("4 equal"));
660 assert_eq!(other.mac_filter_lists, ["MACS"]);
661 assert_eq!(other.multicast_scoping.as_deref(), Some("link-local"));
662 assert_eq!(other.rtf_prefix_lists, ["RTF route-targets"]);
663 assert_eq!(other.source_address_filter_lists, ["SOURCES"]);
664
665 let bare = from_of(&options, 0, 2);
666 assert!(bare.external);
667 assert_eq!(bare.external_type, None);
668 }
669
670 #[test]
671 fn reads_to_conditions_with_the_same_statements() {
672 let options = parse(
673 "policy-options {\n policy-statement export {\n to {\n level 1;\n interface ge-0/0/0.0;\n }\n }\n}\n",
674 );
675 let to = &options.policy_statements[0].terms[0].to;
676 assert_eq!(to.level.as_deref(), Some("1"));
677 assert_eq!(to.interfaces, ["ge-0/0/0.0"]);
678 }
679
680 const DOC_VALIDATION: &str = r#"
683policy-options {
684 policy-statement validation {
685 term valid {
686 from {
687 protocol bgp;
688 validation-database valid;
689 }
690 then {
691 validation-state valid;
692 community add origin-validation-state-valid;
693 accept;
694 }
695 }
696 term invalid {
697 from {
698 protocol bgp;
699 validation-database invalid;
700 }
701 then reject;
702 }
703 term unknown {
704 from protocol bgp;
705 then accept;
706 }
707 }
708}
709"#;
710
711 #[test]
712 fn reads_the_guide_validation_database() {
713 let options = parse(DOC_VALIDATION);
714 assert_eq!(from_of(&options, 0, 0).protocols, ["bgp"]);
715 assert_eq!(from_of(&options, 0, 0).validation_database.as_deref(), Some("valid"));
716 assert_eq!(from_of(&options, 0, 1).validation_database.as_deref(), Some("invalid"));
717 assert_eq!(from_of(&options, 0, 2).validation_database, None);
718 assert_eq!(from_of(&options, 0, 0).validation_database_instance, None);
719 }
720
721 #[test]
724 fn reads_the_validation_database_instance() {
725 let options = parse(
726 r#"
727policy-options {
728 policy-statement rpki {
729 term t {
730 from {
731 validation-database-instance {
732 database RPKI1 state valid;
733 database "RPKI 2";
734 state invalid;
735 }
736 }
737 }
738 term inline {
739 from validation-database valid;
740 }
741 }
742}
743"#,
744 );
745 let instance = from_of(&options, 0, 0).validation_database_instance.as_ref().unwrap();
746 assert_eq!(instance.state.as_deref(), Some("invalid"));
747 assert_eq!(instance.databases.len(), 2);
748 assert_eq!(instance.databases[0].name, "RPKI1");
749 assert_eq!(instance.databases[0].state.as_deref(), Some("valid"));
750 assert_eq!(instance.databases[1].name, "RPKI 2");
751 assert_eq!(instance.databases[1].state, None);
752 assert_eq!(from_of(&options, 0, 1).validation_database_instance, None);
753 }
754
755 fn then_of(options: &PolicyOptions, policy: usize, term: usize) -> &PolicyActions {
756 &options.policy_statements[policy].terms[term].then
757 }
758
759 const DOC_THEN_ACTIONS: &str = r#"
764policy-options {
765 policy-statement aggregate_bw_and_limit_capacity {
766 then {
767 aggregate-bandwidth;
768 limit-bandwidth 80000000;
769 accept;
770 }
771 }
772 policy-statement s2b {
773 from protocol [ static direct ];
774 then {
775 as-path-expand 2;
776 accept;
777 }
778 }
779 policy-statement aigp {
780 term 10 {
781 from {
782 protocol static;
783 route-filter 44.0.0.0/24 exact;
784 }
785 then {
786 aigp-originate distance 200;
787 next-hop 10.100.1.4;
788 accept;
789 }
790 }
791 }
792 policy-statement dampPolicy {
793 term term1 {
794 from {
795 family inet-mvpn;
796 nlri-route-type [ 3 4 5 ];
797 }
798 then accept;
799 }
800 then {
801 damping no-damp;
802 accept;
803 }
804 }
805 policy-statement override-ptx-series-default {
806 term 1 {
807 from {
808 prefix-list install-bgp;
809 }
810 then {
811 load-balance per-prefix;
812 install-to-fib;
813 }
814 }
815 }
816 policy-statement junos-ptx-series-default {
817 term t1 {
818 from {
819 protocol bgp;
820 rib inet.0;
821 }
822 then no-install-to-fib;
823 }
824 }
825 policy-statement damp {
826 term 1 {
827 from {
828 route-filter 10.128.0.0/9 exact damping dry;
829 route-filter 0.0.0.0/0 prefix-length-range /17-/32 damping aggressive;
830 }
831 }
832 }
833}
834"#;
835
836 #[test]
837 fn reads_the_guide_bandwidth_and_expand_actions() {
838 let options = parse(DOC_THEN_ACTIONS);
839 let bandwidth = then_of(&options, 0, 0);
840 assert!(bandwidth.aggregate_bandwidth);
841 assert_eq!(bandwidth.limit_bandwidth.as_deref(), Some("80000000"));
842 assert_eq!(bandwidth.action, Some(PolicyAction::Accept));
843
844 let expand = then_of(&options, 1, 0);
845 assert_eq!(expand.as_path_expand.as_deref(), Some("2"));
846 assert!(!expand.aggregate_bandwidth);
847 }
848
849 #[test]
850 fn reads_the_guide_aigp_originate() {
851 let options = parse(DOC_THEN_ACTIONS);
852 let then = then_of(&options, 2, 0);
853 assert!(then.aigp_originate);
854 assert_eq!(then.aigp_distance.as_deref(), Some("200"));
855 assert_eq!(then.next_hop.as_deref(), Some("10.100.1.4"));
856 }
857
858 #[test]
859 fn reads_the_guide_damping() {
860 let options = parse(DOC_THEN_ACTIONS);
861 let policy = &options.policy_statements[3];
862 assert_eq!(policy.terms.len(), 2);
863 assert_eq!(policy.terms[0].name.as_deref(), Some("term1"));
864 assert_eq!(policy.terms[1].name, None);
865 assert_eq!(policy.terms[1].then.damping.as_deref(), Some("no-damp"));
866 assert_eq!(policy.terms[1].then.action, Some(PolicyAction::Accept));
867
868 let filters = &from_of(&options, 6, 0).route_filters;
869 assert_eq!(filters[0].match_type.as_deref(), Some("exact damping dry"));
870 assert_eq!(
871 filters[1].match_type.as_deref(),
872 Some("prefix-length-range /17-/32 damping aggressive")
873 );
874 }
875
876 #[test]
877 fn reads_the_guide_install_to_fib() {
878 let options = parse(DOC_THEN_ACTIONS);
879 let override_default = then_of(&options, 4, 0);
880 assert_eq!(override_default.load_balance.as_deref(), Some("per-prefix"));
881 assert_eq!(override_default.install_to_fib, Some(true));
882 assert_eq!(then_of(&options, 5, 0).install_to_fib, Some(false));
883 assert_eq!(then_of(&options, 0, 0).install_to_fib, None);
884 }
885
886 #[test]
889 fn reads_the_other_actions() {
890 let options = parse(
891 r#"
892policy-options {
893 policy-statement actions {
894 term a {
895 then {
896 default-action reject;
897 add-path send-count 4;
898 advertise-locator;
899 aggregate-weight {
900 multiplier 2;
901 }
902 as-path-expand last-as count 3;
903 assisted-replication replicator-ip 192.0.2.1 strict;
904 bgp-output-queue-priority 5;
905 class gold;
906 color 10 color2 20;
907 cos-next-hop-map MAP;
908 destination-class DC;
909 dynamic-tunnel-attributes TUNNEL;
910 external type 2 metric 10;
911 forwarding-class expedited-forwarding;
912 install-nexthop strict lsp LSP1;
913 map-to-interface self;
914 no-entropy-label-capability;
915 origin igp;
916 preference add 5;
917 prefix-attribute-flags;
918 prefix-segment {
919 index 100;
920 node-segment;
921 }
922 priority high;
923 set-down-bit;
924 source-class SC;
925 sr-te-template TEMPLATE;
926 ssm-source [ 192.0.2.1 192.0.2.2 ];
927 tag 100 tag2 200;
928 validation-state valid;
929 }
930 }
931 }
932}
933"#,
934 );
935 let then = then_of(&options, 0, 0);
936 assert_eq!(then.default_action, Some(PolicyAction::Reject));
937 assert_eq!(then.add_path.as_deref(), Some("send-count 4"));
938 assert!(then.advertise_locator);
939 assert_eq!(then.aggregate_weight.as_deref(), Some("2"));
940 assert!(!then.aigp_originate);
941 assert_eq!(then.as_path_expand.as_deref(), Some("last-as count 3"));
942 assert_eq!(
943 then.assisted_replication.as_deref(),
944 Some("replicator-ip 192.0.2.1 strict")
945 );
946 assert_eq!(then.bgp_output_queue_priority.as_deref(), Some("5"));
947 assert_eq!(then.class.as_deref(), Some("gold"));
948 assert_eq!(then.color.as_deref(), Some("10 color2 20"));
949 assert_eq!(then.cos_next_hop_map.as_deref(), Some("MAP"));
950 assert_eq!(then.destination_class.as_deref(), Some("DC"));
951 assert_eq!(then.dynamic_tunnel_attributes.as_deref(), Some("TUNNEL"));
952 assert_eq!(then.external.as_deref(), Some("type 2 metric 10"));
953 assert_eq!(then.forwarding_class.as_deref(), Some("expedited-forwarding"));
954 assert_eq!(then.install_nexthop.as_deref(), Some("strict lsp LSP1"));
955 assert_eq!(then.map_to_interface.as_deref(), Some("self"));
956 assert!(then.no_entropy_label_capability);
957 assert_eq!(then.origin.as_deref(), Some("igp"));
958 assert_eq!(then.preference.as_deref(), Some("add 5"));
959 assert!(then.prefix_attribute_flags);
960 let segment = then.prefix_segment.as_ref().unwrap();
961 assert_eq!(segment.index.as_deref(), Some("100"));
962 assert!(segment.node_segment);
963 assert_eq!(then.priority.as_deref(), Some("high"));
964 assert!(then.set_down_bit);
965 assert_eq!(then.source_class.as_deref(), Some("SC"));
966 assert_eq!(then.sr_te_template.as_deref(), Some("TEMPLATE"));
967 assert_eq!(then.ssm_sources, ["192.0.2.1", "192.0.2.2"]);
968 assert_eq!(then.tag.as_deref(), Some("100 tag2 200"));
969 assert_eq!(then.validation_state.as_deref(), Some("valid"));
970 }
971
972 #[test]
974 fn reads_community_lists_and_symbols() {
975 let options = parse(
976 "policy-options {\n policy-statement c {\n then {\n community add [ a b ];\n community - old;\n community = only;\n }\n }\n}\n",
977 );
978 let communities: Vec<_> = then_of(&options, 0, 0)
979 .communities
980 .iter()
981 .map(|c| (c.operation, c.community.as_str()))
982 .collect();
983 assert_eq!(
984 communities,
985 [
986 (CommunityOperation::Add, "a"),
987 (CommunityOperation::Add, "b"),
988 (CommunityOperation::Delete, "old"),
989 (CommunityOperation::Set, "only"),
990 ]
991 );
992 }
993}