Skip to main content

asterust_junos/policy_options/
mod.rs

1//! `policy-options`
2//! `policy-options { ... }`.
3//!
4//! # See also
5//!
6//! - [`[edit policy-options]` hierarchy](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/topic-map/hierarchy-edit-policy-options.html)
7
8mod as_path;
9mod as_path_group;
10mod community;
11mod policy_statement;
12mod prefix_list;
13mod resolution_map;
14
15pub use as_path::AsPath;
16pub use as_path_group::AsPathGroup;
17pub use community::Community;
18pub use policy_statement::{
19    CommunityAction, CommunityOperation, PolicyAction, PolicyActions, PolicyConditions, PolicySrv6Action,
20    PolicyStatement, PolicyTerm, RouteFilter,
21};
22pub use prefix_list::PrefixList;
23pub use resolution_map::ResolutionMap;
24
25use crate::{active_children, named_children, top_level};
26use as_path::parse_as_path;
27use as_path_group::parse_as_path_group;
28use asterust::config::Config;
29use community::parse_community;
30use policy_statement::parse_policy;
31use prefix_list::parse_prefix_list;
32use resolution_map::parse_resolution_map;
33
34/// The top-level `policy-options` configuration.
35#[derive(Clone, Debug, PartialEq, Eq)]
36#[non_exhaustive]
37pub struct PolicyOptions {
38    pub policy_statements: Vec<PolicyStatement>,
39    pub communities: Vec<Community>,
40    pub prefix_lists: Vec<PrefixList>,
41    pub as_paths: Vec<AsPath>,
42    pub as_path_groups: Vec<AsPathGroup>,
43    pub resolution_maps: Vec<ResolutionMap>,
44}
45
46/// Returns the top-level `policy-options` block, or `None` if there is none.
47///
48/// # Examples
49///
50/// ```
51/// use asterust::config::juniper;
52/// use asterust_junos::policy_options::policy_options;
53///
54/// let config = juniper::parse_braces("policy-options {\n    prefix-list CUSTOMERS {\n        192.0.2.0/24;\n    }\n}\n");
55/// let options = policy_options(&config).unwrap();
56/// assert_eq!(options.prefix_lists[0].name, "CUSTOMERS");
57/// assert_eq!(options.prefix_lists[0].prefixes, ["192.0.2.0/24"]);
58/// ```
59pub fn policy_options(config: &Config) -> Option<PolicyOptions> {
60    let root = top_level(config, "policy-options")?;
61    Some(PolicyOptions {
62        policy_statements: named_children(root, "policy-statement")
63            .map(|(name, line)| parse_policy(name, line))
64            .collect(),
65        communities: active_children(root).filter_map(parse_community).collect(),
66        prefix_lists: named_children(root, "prefix-list")
67            .map(|(name, line)| parse_prefix_list(name, line))
68            .collect(),
69        as_paths: active_children(root).filter_map(parse_as_path).collect(),
70        as_path_groups: named_children(root, "as-path-group")
71            .map(|(name, line)| parse_as_path_group(name, line))
72            .collect(),
73        resolution_maps: named_children(root, "resolution-map")
74            .map(|(name, line)| parse_resolution_map(name, line))
75            .collect(),
76    })
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use asterust::config::juniper;
83
84    fn parse(text: &str) -> PolicyOptions {
85        policy_options(&juniper::parse_braces(text)).expect("fixture has a policy-options block")
86    }
87
88    // Adapted from Juniper's BGP User Guide "Routing Policies for BGP Communities"; see the README "Sources".
89    const DOC_COMMUNITY_TAG: &str = r#"
90policy-options {
91    policy-statement Edu-to-isis {
92        term 1 {
93            from {
94                protocol bgp;
95                community Edu;
96            }
97            then {
98                metric 63;
99                accept;
100            }
101        }
102    }
103    policy-statement send-isis-and-direct {
104        term 1 {
105            from {
106                protocol [ isis direct ];
107                route-filter 10.0.0.0/16 orlonger;
108                route-filter 192.168.0.0/16 orlonger;
109            }
110            then accept;
111        }
112    }
113    community Edu members 2:5;
114}
115"#;
116
117    #[test]
118    fn doc_term_with_from_block_and_metric() {
119        let options = parse(DOC_COMMUNITY_TAG);
120        assert_eq!(options.policy_statements.len(), 2);
121
122        let policy = &options.policy_statements[0];
123        assert_eq!(policy.name, "Edu-to-isis");
124        let term = &policy.terms[0];
125        assert_eq!(term.name.as_deref(), Some("1"));
126        assert_eq!(term.from.protocols, ["bgp"]);
127        assert_eq!(term.from.communities, ["Edu"]);
128        assert_eq!(term.then.metric.as_deref(), Some("63"));
129        assert_eq!(term.then.action, Some(PolicyAction::Accept));
130    }
131
132    #[test]
133    fn doc_protocol_list_route_filters_and_leaf_then() {
134        let options = parse(DOC_COMMUNITY_TAG);
135        let term = &options.policy_statements[1].terms[0];
136        assert_eq!(term.from.protocols, ["isis", "direct"]);
137        assert_eq!(term.from.route_filters.len(), 2);
138        assert_eq!(term.from.route_filters[0].prefix, "10.0.0.0/16");
139        assert_eq!(term.from.route_filters[0].match_type.as_deref(), Some("orlonger"));
140        assert_eq!(term.then.action, Some(PolicyAction::Accept));
141    }
142
143    #[test]
144    fn doc_one_line_community() {
145        let options = parse(DOC_COMMUNITY_TAG);
146        assert_eq!(options.communities.len(), 1);
147        assert_eq!(options.communities[0].name, "Edu");
148        assert_eq!(options.communities[0].members, ["2:5"]);
149        assert!(!options.communities[0].invert_match);
150    }
151
152    // Adapted from the same guide's "Configuring a Routing Policy That Removes BGP Communities" and "...Based on
153    // the Number of BGP Communities" examples (Devices R1 and R2).
154    const DOC_COMMUNITY_ACTIONS: &str = r#"
155policy-options {
156    policy-statement statics {
157        from protocol static;
158        then {
159            community add 1;
160            accept;
161        }
162    }
163    policy-statement remove-communities {
164        term 1 {
165            from protocol bgp;
166            then {
167                community delete wild;
168                accept;
169            }
170        }
171        term 2 {
172            then reject;
173        }
174    }
175    community wild members *:*;
176    community 1 members [ 2:1 2:2 2:3 ];
177}
178"#;
179
180    #[test]
181    fn doc_policy_without_terms_has_one_unnamed_term() {
182        let options = parse(DOC_COMMUNITY_ACTIONS);
183        let statics = &options.policy_statements[0];
184        assert_eq!(statics.terms.len(), 1);
185        let term = &statics.terms[0];
186        assert_eq!(term.name, None);
187        assert_eq!(term.from.protocols, ["static"]);
188        assert_eq!(
189            term.then.communities,
190            [CommunityAction {
191                operation: CommunityOperation::Add,
192                community: "1".to_string()
193            }]
194        );
195        assert_eq!(term.then.action, Some(PolicyAction::Accept));
196    }
197
198    #[test]
199    fn doc_community_delete_and_final_reject_term() {
200        let options = parse(DOC_COMMUNITY_ACTIONS);
201        let remove = &options.policy_statements[1];
202        assert_eq!(remove.terms.len(), 2);
203        assert_eq!(
204            remove.terms[0].then.communities[0].operation,
205            CommunityOperation::Delete
206        );
207        assert_eq!(remove.terms[0].then.communities[0].community, "wild");
208        assert_eq!(remove.terms[1].name.as_deref(), Some("2"));
209        assert_eq!(remove.terms[1].then.action, Some(PolicyAction::Reject));
210    }
211
212    #[test]
213    fn doc_community_members_list() {
214        let options = parse(DOC_COMMUNITY_ACTIONS);
215        assert_eq!(options.communities[0].members, ["*:*"]);
216        assert_eq!(options.communities[1].name, "1");
217        assert_eq!(options.communities[1].members, ["2:1", "2:2", "2:3"]);
218    }
219
220    // Not from documentation: covers statements the Juniper examples do not use. See the README "Sources".
221    const CONFIG: &str = r#"
222policy-options {
223    prefix-list CUSTOMERS {
224        192.0.2.0/24;
225        2001:db8::/32;
226    }
227    prefix-list DYNAMIC {
228        apply-path "protocols bgp group <*> neighbor <*>";
229    }
230    as-path FROM-AS65001 ".* 65001";
231    as-path-group TRANSIT {
232        as-path TIER1 "65100 .*";
233        as-path TIER2 "65200 .*";
234    }
235    community BLOCK {
236        invert-match;
237        members [ no-export 65000:666 ];
238    }
239    community WILD members "* : *";
240    policy-statement IMPORT {
241        term FROM-CUSTOMER {
242            from {
243                family inet;
244                neighbor 192.0.2.1;
245                prefix-list CUSTOMERS;
246                prefix-list-filter CUSTOMERS orlonger;
247                as-path FROM-AS65001;
248                route-filter 10.0.0.0/8 upto /24;
249                policy SUBROUTINE;
250            }
251            then {
252                local-preference 200;
253                next-hop self;
254                as-path-prepend "65000 65000";
255                next policy;
256            }
257        }
258        inactive: term DISABLED {
259            then reject;
260        }
261        term SKIP {
262            from protocol ospf;
263            then next term;
264        }
265        then reject;
266    }
267}
268"#;
269
270    #[test]
271    fn extracts_prefix_lists_and_as_paths() {
272        let options = parse(CONFIG);
273        assert_eq!(options.prefix_lists[0].name, "CUSTOMERS");
274        assert_eq!(options.prefix_lists[0].prefixes, ["192.0.2.0/24", "2001:db8::/32"]);
275        assert_eq!(options.prefix_lists[0].apply_path, None);
276        assert!(options.prefix_lists[1].prefixes.is_empty());
277        assert_eq!(
278            options.prefix_lists[1].apply_path.as_deref(),
279            Some("protocols bgp group <*> neighbor <*>")
280        );
281
282        assert_eq!(options.as_paths.len(), 1);
283        assert_eq!(options.as_paths[0].name, "FROM-AS65001");
284        assert_eq!(options.as_paths[0].regex, ".* 65001");
285        let group = &options.as_path_groups[0];
286        assert_eq!(group.name, "TRANSIT");
287        let names: Vec<_> = group.as_paths.iter().map(|p| p.name.as_str()).collect();
288        assert_eq!(names, ["TIER1", "TIER2"]);
289        assert_eq!(group.as_paths[1].regex, "65200 .*");
290    }
291
292    #[test]
293    fn extracts_block_and_quoted_communities() {
294        let options = parse(CONFIG);
295        assert_eq!(options.communities.len(), 2);
296        assert_eq!(options.communities[0].name, "BLOCK");
297        assert_eq!(options.communities[0].members, ["no-export", "65000:666"]);
298        assert!(options.communities[0].invert_match);
299        assert_eq!(options.communities[1].members, ["* : *"]);
300    }
301
302    #[test]
303    fn extracts_conditions_and_manipulation_actions() {
304        let options = parse(CONFIG);
305        let term = &options.policy_statements[0].terms[0];
306        assert_eq!(term.name.as_deref(), Some("FROM-CUSTOMER"));
307        assert_eq!(term.from.families, ["inet"]);
308        assert_eq!(term.from.neighbors, ["192.0.2.1"]);
309        assert_eq!(term.from.prefix_lists, ["CUSTOMERS"]);
310        assert_eq!(term.from.prefix_list_filters, ["CUSTOMERS orlonger"]);
311        assert_eq!(term.from.as_paths, ["FROM-AS65001"]);
312        assert_eq!(term.from.route_filters[0].match_type.as_deref(), Some("upto /24"));
313        assert_eq!(term.from.policies, ["SUBROUTINE"]);
314        assert_eq!(term.then.local_preference.as_deref(), Some("200"));
315        assert_eq!(term.then.next_hop.as_deref(), Some("self"));
316        assert_eq!(term.then.as_path_prepend.as_deref(), Some("65000 65000"));
317        assert_eq!(term.then.action, Some(PolicyAction::NextPolicy));
318    }
319
320    #[test]
321    fn skips_inactive_terms_and_keeps_unnamed_final_term_last() {
322        let options = parse(CONFIG);
323        let terms = &options.policy_statements[0].terms;
324        let names: Vec<_> = terms.iter().map(|t| t.name.as_deref()).collect();
325        assert_eq!(names, [Some("FROM-CUSTOMER"), Some("SKIP"), None]);
326        assert_eq!(terms[1].then.action, Some(PolicyAction::NextTerm));
327        assert_eq!(terms[2].then.action, Some(PolicyAction::Reject));
328    }
329
330    #[test]
331    fn no_policy_options_is_none() {
332        assert!(policy_options(&juniper::parse_braces("system {\n host-name r1;\n}\n")).is_none());
333    }
334
335    // Device R1 `show policy-options` of "Example: Configuring Static SR-TE Policy for an SRv6 Tunnel" (BGP User Guide,
336    // BGP Egress Traffic Engineering), with the guide's column padding removed; see the README "Sources".
337    const DOC_SRV6_TE: &str = r#"
338policy-options {
339    policy-statement LBPP {
340        term 1 {
341            then {
342                load-balance per-packet;
343            }
344        }
345    }
346    policy-statement mpath-resolve {
347        then multipath-resolve;
348    }
349    policy-statement v4vpn1_res_map1 {
350        term 1 {
351            from protocol bgp;
352            then {
353                accept;
354                resolution-map map1;
355            }
356        }
357    }
358    policy-statement v6vpn1_res_map1 {
359        term 1 {
360            from {
361                family inet6-vpn;
362                protocol bgp;
363            }
364            then {
365                accept;
366                resolution-map map1;
367            }
368        }
369    }
370    community to_CE0_community members target:65500:1;
371    resolution-map map1 {
372        mode ip-color;
373    }
374}
375"#;
376
377    // Not from documentation: the `srv6` action is written from the uSID example at srv6.md and the `resolution-map`
378    // list from the CLI Reference. See the README "Sources".
379    const SRV6_ACTION: &str = r#"
380policy-options {
381    policy-statement LL-PREFIXES {
382        term VOICE {
383            from community VOICE;
384            then {
385                srv6 locator LOC128 micro-dt46-sid;
386                accept;
387            }
388        }
389        term STATIC {
390            then srv6 locator LOC1 end-dt4-sid 3001::4;
391        }
392        term PLAIN {
393            then srv6 locator LOC2;
394        }
395    }
396    resolution-map map2 {
397        mode [ color-only ip-color ];
398    }
399}
400"#;
401
402    #[test]
403    fn doc_load_balance_and_multipath_resolve() {
404        let options = parse(DOC_SRV6_TE);
405        let balance = &options.policy_statements[0].terms[0].then;
406        assert_eq!(balance.load_balance.as_deref(), Some("per-packet"));
407        assert!(!balance.multipath_resolve);
408
409        let resolve = &options.policy_statements[1].terms[0].then;
410        assert!(resolve.multipath_resolve);
411        assert_eq!(resolve.load_balance, None);
412    }
413
414    #[test]
415    fn doc_resolution_map_action_and_definition() {
416        let options = parse(DOC_SRV6_TE);
417        let term = &options.policy_statements[3].terms[0];
418        assert_eq!(term.from.families, ["inet6-vpn"]);
419        assert_eq!(term.then.resolution_map.as_deref(), Some("map1"));
420        assert_eq!(term.then.action, Some(PolicyAction::Accept));
421
422        assert_eq!(options.resolution_maps.len(), 1);
423        assert_eq!(options.resolution_maps[0].name, "map1");
424        assert_eq!(options.resolution_maps[0].modes, ["ip-color"]);
425    }
426
427    #[test]
428    fn srv6_actions() {
429        let options = parse(SRV6_ACTION);
430        let terms = &options.policy_statements[0].terms;
431
432        let dynamic = terms[0].then.srv6.as_ref().unwrap();
433        assert_eq!(dynamic.locator, "LOC128");
434        assert_eq!(dynamic.sid_type.as_deref(), Some("micro-dt46-sid"));
435        assert_eq!(dynamic.sid_value, None);
436        assert_eq!(terms[0].then.action, Some(PolicyAction::Accept));
437
438        let fixed = terms[1].then.srv6.as_ref().unwrap();
439        assert_eq!(fixed.locator, "LOC1");
440        assert_eq!(fixed.sid_type.as_deref(), Some("end-dt4-sid"));
441        assert_eq!(fixed.sid_value.as_deref(), Some("3001::4"));
442
443        let bare = terms[2].then.srv6.as_ref().unwrap();
444        assert_eq!(bare.locator, "LOC2");
445        assert_eq!(bare.sid_type, None);
446
447        assert_eq!(options.resolution_maps[0].modes, ["color-only", "ip-color"]);
448    }
449}